javascript Array() 与 new Array()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8205691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Array() vs new Array()
提问by scravy
What is the difference (if there is any) between
之间有什么区别(如果有的话)
x = Array()
and
和
x = new Array()
Which one should I use?
我应该使用哪一种?
回答by SLaks
The specsays:
该规范说:
When
Array
is called as a function rather than as a constructor, it creates and initialises a new Array object. Thus the function callArray(…)
is equivalent to the object creation expressionnew Array(…)
with the same arguments.
当
Array
作为函数而不是构造函数调用时,它会创建并初始化一个新的 Array 对象。因此,函数调用Array(…)
等效于new Array(…)
具有相同参数的对象创建表达式。
回答by Ricardo Tomasi
You should use the literal []
. Reasons are outlined here. Using the Array()
constructor can be ambiguous, since it accepts either a length
or a list of elements:
您应该使用文字[]
. 此处概述了原因。使用Array()
构造函数可能会有歧义,因为它接受一个length
或一个元素列表:
new Array(5) // []
new Array('5') // ['5']
[5] // [5]
['5'] // ['5']
The reason you can use Array
without the new
operator is that internally it does a common trick with constructors:
您可以在Array
没有new
运算符的情况下使用的原因是它在内部对构造函数执行了一个常见的技巧:
function Thing(){
if (!(this instanceof Thing)){
return new Thing()
}
// ... define object
}
That is, if you call Thing()
it will call new Thing()
for you.
也就是说,如果你打电话,Thing()
它会打电话new Thing()
给你。
回答by Ry-
I believe that both are equivalent. However, in JavaScript at least, you should always use the literal syntax:
我相信两者是等价的。但是,至少在 JavaScript 中,您应该始终使用文字语法:
x = []
But based on some tests in the browsers I have, Array(1, 2, 3)
gives the same result as new Array(1, 2, 3)
, and same with Array(15)
and new Array(15)
. Or just plain newArray()
.
但基于在我的浏览器的一些测试,Array(1, 2, 3)
给出了相同的结果new Array(1, 2, 3)
,并与同Array(15)
和new Array(15)
。或者只是简单的newArray()
。