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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:38:40  来源:igfitidea点击:

Array() vs new Array()

javascriptarrays

提问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 Arrayis called as a function rather than as a constructor, it creates and initialises a new Array object. Thus the function call Array(…)is equivalent to the object creation expression new 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 lengthor a list of elements:

您应该使用文字[]. 此处概述原因。使用Array()构造函数可能会有歧义,因为它接受一个length或一个元素列表:

new Array(5)   // []
new Array('5') // ['5']

[5]   // [5]
['5'] // ['5']

The reason you can use Arraywithout the newoperator 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()