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 数组时?
基础教程推荐
- Bokeh Div文本对齐 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
