Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/402.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript中的数组文字符号是什么?什么时候应该使用它?_Javascript_Arrays_Jslint_Literals - Fatal编程技术网

javascript中的数组文字符号是什么?什么时候应该使用它?

javascript中的数组文字符号是什么?什么时候应该使用它?,javascript,arrays,jslint,literals,Javascript,Arrays,Jslint,Literals,JSLint给了我这个错误: 第11行第33个字符出现问题:使用数组文字符号[] 什么是数组文字符号,为什么要我用它来代替 这里显示newarray()应该可以正常工作。。。有什么我遗漏的吗?数组文字表示法就是用空括号定义一个新数组。在您的示例中: var myArray = []; 这是定义数组的“新”方法,我认为它更短/更干净 下面的例子解释了它们之间的区别: var a = [], // these are the same b = new Array(),

JSLint给了我这个错误:

第11行第33个字符出现问题:使用数组文字符号[]

什么是数组文字符号,为什么要我用它来代替


这里显示
newarray()应该可以正常工作。。。有什么我遗漏的吗?

数组文字表示法就是用空括号定义一个新数组。在您的示例中:

var myArray = [];
这是定义数组的“新”方法,我认为它更短/更干净

下面的例子解释了它们之间的区别:

var a = [],            // these are the same
    b = new Array(),   // a and b are arrays with length 0

    c = ['foo', 'bar'],           // these are the same
    d = new Array('foo', 'bar'),  // c and d are arrays with 2 strings

    // these are different:
    e = [3],             // e.length == 1, e[0] == 3
    f = new Array(3);   // f.length == 3, f[0] == undefined
参考

另见:


除了Crockford的论点,我相信这也是因为其他语言有相似的数据结构,恰好使用相同的语法;例如请参见以下示例:

// this is a Python list
a = [66.25, 333, 333, 1, 1234.5]

// this is a Python dictionary
tel = {'jack': 4098, 'sape': 4139}
Python在语法上也是正确的Javascript,这不是很好吗?(是的,缺少结尾分号,但Javascript也不需要这些分号)


因此,通过在编程中重用常见的范例,我们可以避免每个人都必须重新学习不应该学习的东西。

除了Crockford参数之外,jsPerf说它更快

在查看@ecMode jsperf之后,我做了一些进一步的测试

在Chrome上使用push添加到阵列时,new array()的速度要快得多:


对于[],使用索引进行添加的速度稍快。

这类似于,但不完全相同:的副本也总是尽可能使用文本,因为数组构造函数(new Array())并不总是正常工作。e、 g.如果有一个值是一个数字。>新数组(3,11,8)[3,11,8]>新数组(3)[,,]>新数组(3.1)RangeError:无效数组长度这是“新”的方式…没有双关语的意思?但答案没有解释何时应该使用文字,即[]以及何时使用新数组();始终使用文字
[]
。这样做更好的原因是它更安全,因为有人可能会覆盖
window.Array
构造函数,但不会覆盖文本。对于那些使用TypeScript的人来说,等价物是
var a:string[]=[]。感谢您的解释。回答得好!
// this is a Python list
a = [66.25, 333, 333, 1, 1234.5]

// this is a Python dictionary
tel = {'jack': 4098, 'sape': 4139}