17

I remember reading somewhere (I think it was in one of Crockford's papers) that using an array literal [] is better than using the new Array(); notation.

But I can't really remember any advantages of one over the other.

Can anyone please explain to me on why the former is preferred over the latter?

Here is one reason I can think of on why [] is better than new Array();:

var Array = function () { };

Overriding the Array object will break code...!

Any more reasons?

4

4 回答 4

36

简洁

它通过网络传输的字节更少,解释的字节更少,解析它的心理资源也更少。

少即是多。

一致性

这两行代码有什么区别?

var arr = [5];
var arr = new Array(5);

根据这里 new Array(5);不会返回一个包含 5 的数组,而是返回一个 5 元素数组,所有元素都是undefined. 而这两行返回相同的数组。

var arr = [5,6];
var arr = new Array(5,6);
于 2009-11-25T23:14:21.600 回答
24

一个很好的理由是因为 Array 构造函数具有完全不直观的行为。例如:

var a = new Array(5);
console.log(a.length); //prints "5"
console.log(a[0]); //prints "undefined"

var b = new Array(1,2);
console.log(b.length); //prints "2"
console.log(b[0]); //prints "1"

在这种情况下,a 最终成为一个大小为 5 且所有元素未定义的数组,而 b 最终成为一个大小为 2 的数组,其值为 [1,2]。

var c = new Array("5");
console.log(c.length); //prints "1"
console.log(c[0]); //prints "5"

在这里,你最终得到一个包含“5”的单元素数组

通常,您可能永远不应该在 Javascript 中的内置类型上使用构造函数。他们都有像这样奇怪的边缘情况。例如:

var s = new String("Hello");
var l = "Hello";
console.log(typeof(s)); // prints "object"
console.log(typeof(l)); // prints "string"
于 2009-11-26T00:04:40.390 回答
9

优雅

简而言之,它看起来更好,程序员更容易解析,尤其是对于更复杂的数据结构:

var a = [
    ['a list', 'of', 'strings'],
    [1, 2, 3, 4],
    { hello: "This is an object property." }
];

与笨拙的面向 OOP 的方法相比:

var a = new Array();
var a2 = new Array();

a2.push('a list');
a2.push('of');
a2.push('strings');

var a3 = new Array();
a3.push(1);
a3.push(2);
a3.push(3);
a3.push(4);

var o = new Object();
o.hello = "This is an object property";
a.push(a2, a3, o);
于 2009-11-25T23:44:23.490 回答
-1

new Array(1, 2, 3)代替与代替[1, 2, 3]相同new String("cow")"cow"

于 2009-11-25T23:55:26.727 回答