What’s the difference between quot;Array()quot; and quot;[]quot; while declaring a JavaScript array?(“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.
这篇关于“Array()"和“Array()"有什么区别?和“[]"在声明一个 JavaScript 数组时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“Array()"和“Array()"有什么区别?和“[]"在声明一个 JavaScript 数组时?
基础教程推荐
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 动态更新多个选择框 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01