71

JSLint 给了我这个错误:

第 11 行字符 33 处的问题:使用数组文字符号 []。

var myArray = new Array();

什么是数组文字表示法,为什么它要我使用它?

它在这里显示new Array();应该可以正常工作......我有什么遗漏吗?

4

4 回答 4

105

数组文字表示法是您仅使用空括号定义新数组的地方。在您的示例中:

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

参考声明 JavaScript 数组时,“Array()”和“[]”有什么区别?

于 2009-07-07T20:38:53.420 回答
23

另请参阅:var x = new Array(); 有什么问题?

除了 Crockford 的论点,我相信这也是因为其他语言有类似的数据结构,碰巧使用相同的语法。例如,Python 有列表和字典;请参阅以下示例:

// 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 也不需要这些分号)

因此,通过在编程中重用通用范式,我们使每个人都不必重新学习不应该学习的东西。

于 2009-07-07T23:19:46.637 回答
3

除了 Crockford 的论点,jsPerf 说它更快。http://jsperf.com/new-vs-literal-array-declaration

于 2014-01-04T06:29:08.353 回答
0

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

当使用 push 添加到数组时,新的 Array() 在 Chrome 上要快得多:

http://jsperf.com/new-vs-literal-array-declaration/2

[] 使用索引添加稍微快一些。

于 2014-04-25T14:22:16.007 回答