“Array()"和“Array()"有什么区别?和“[]"在声明一个 JavaScript 数组时?
这样声明数组的真正区别是什么:
What's the real difference between declaring an array like this:
var myArray = new Array();
和
var myArray = [];
推荐答案
有区别,但那个例子没有区别.
There is a difference, but there is no difference in that example.
使用更详细的方法:new Array()
在参数中确实有一个额外的选项:如果您将一个数字传递给构造函数,您将得到一个该长度的数组:
Using the more verbose method: new Array()
does have one extra option in the parameters: if you pass a number to the constructor, you will get an array of that length:
x = new Array(5);
alert(x.length); // 5
为了说明创建数组的不同方法:
To illustrate the different ways to create an array:
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()
时,您可以设置数组的大小,这会影响堆栈大小.如果您遇到堆栈溢出(Array.push 与 Array.unshift 的性能),这会很有用当数组的大小超过堆栈的大小时,必须重新创建它.所以实际上,根据用例,使用 new Array()
可以提高性能,因为您可以防止发生溢出.
Another difference is that when using new Array()
you're able to set the size of the array, which affects the stack size. This can be useful if you're getting stack overflows (Performance of Array.push vs Array.unshift) which is what happens when the size of the array exceeds the size of the stack, and it has to be re-created. So there can actually, depending on the use case, be a performance increase when using new Array()
because you can prevent the overflow from happening.
正如 this answer 中指出的,new Array(5)
实际上不会添加将五个 undefined
项添加到数组中.它只是为五个项目增加了空间.请注意,以这种方式使用 Array
会导致难以依赖 array.length
进行计算.
As pointed out in this answer, new Array(5)
will not actually add five undefined
items to the array. It simply adds space for five items. Be aware that using Array
this way makes it difficult to rely on array.length
for calculations.
相关文章