这样声明数组的真正区别是什么:
var myArray = new Array();
和
var myArray = [];
最佳答案
有区别,但在那个例子中没有区别。
使用更详细的方法:new Array()
在参数中确实有一个额外的选项:如果您将一个数字传递给构造函数,您将得到一个该长度的数组:
x = new Array(5);
alert(x.length); // 5
为了说明创建数组的不同方法:
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
;
另一个区别是,当使用 new Array()
时,您可以设置数组的大小,这会影响堆栈大小。如果您遇到堆栈溢出( Performance of Array.push vs Array.unshift ),这可能很有用,这是当数组大小超过堆栈大小时发生的情况,并且必须重新创建它。所以实际上,根据用例,使用 new Array()
可以提高性能,因为您可以防止发生溢出。
正如 this answer 中指出的那样, new Array(5)
实际上不会将五个 undefined
项添加到数组中。它只是为五个项目增加了空间。请注意,以这种方式使用 Array
会导致难以依赖 array.length
进行计算。
关于javascript - 声明 JavaScript 数组时 "Array()"和 "[]"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/931872/