“Array()”和“Array()”有什么区别? 和“[]” 声明 JavaScript 数组时?
像这样声明数组之间的真正区别是什么:
var myArray = new Array();
和
var myArray = [];
What's the real difference between declaring an array like this:
var myArray = new Array();
and
var myArray = [];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(20)
使用隐式数组和数组构造函数创建数组之间的区别很微妙,但很重要。
当您使用创建数组时,
您告诉解释器创建一个新的运行时数组。 根本不需要额外的处理。 完毕。
如果你使用:
你告诉解释器,我想调用构造函数“
Array
”并生成一个对象。 然后,它会查找执行上下文以找到要调用的构造函数,并调用它,创建数组。您可能会想“好吧,这根本不重要。它们是一样的!”。 不幸的是你不能保证这一点。
采取以下示例:
在上面的示例中,第一个呼叫将如您所期望的那样提醒“SPARTA”。 第二个不会。 你最终会看到未定义的。 您还会注意到,b 包含所有本机 Array 对象函数,例如
push
,而另一个则不包含。虽然您可能期望这种情况发生,但它只是说明了
[]
与new Array()
不同的事实。如果您知道只需要一个数组,最好只使用
[]
。 我也不建议四处走动并重新定义数组......The difference between creating an array with the implicit array and the array constructor is subtle but important.
When you create an array using
You're telling the interpreter to create a new runtime array. No extra processing necessary at all. Done.
If you use:
You're telling the interpreter, I want to call the constructor "
Array
" and generate an object. It then looks up through your execution context to find the constructor to call, and calls it, creating your array.You may think "Well, this doesn't matter at all. They're the same!". Unfortunately you can't guarantee that.
Take the following example:
In the above example, the first call will alert 'SPARTA' as you'd expect. The second will not. You will end up seeing undefined. You'll also note that b contains all of the native Array object functions such as
push
, where the other does not.While you may expect this to happen, it just illustrates the fact that
[]
is not the same asnew Array()
.It's probably best to just use
[]
if you know you just want an array. I also do not suggest going around and redefining Array...有一个重要的区别,但还没有答案提到。
由此看来:
您可能会认为
new Array(2)
等同于[undefined, undefined]
,但事实并非如此!让我们尝试一下 <代码>map():
看到了吗? 语义完全不同! 那么这是为什么呢?
根据 ES6 Spec 22.1.1.2,
Array(len)
的工作只是创建一个新数组,其属性length
设置为参数len
就是这样,这意味着这个新创建的数组中没有任何真实元素。函数
map()
,根据规范22.1.3.15,首先会检查HasProperty
,然后调用回调,但事实证明:这就是为什么你不能期望任何迭代函数在从
new Array(len)
创建的数组上照常工作。顺便说一句,Safari 和 Firefox 对于这种情况有更好的“打印”:
我已经向 Chromium 提交了一个问题,并要求他们修复这个令人困惑的打印:
https://bugs.chromium.org/p/chromium/issues/detail ?id=732021
更新:它已经修复了。 Chrome 现在打印为:
There is an important difference that no answer has mentioned yet.
From this:
You might think the
new Array(2)
is equivalent to[undefined, undefined]
, but it's NOT!Let's try with
map()
:See? The semantics are totally different! So why is that?
According to ES6 Spec 22.1.1.2, the job of
Array(len)
is just creating a new array whose propertylength
is set to the argumentlen
and that's it, meaning there isn't any real element inside this newly created array.Function
map()
, according to spec 22.1.3.15 would firstly checkHasProperty
then call the callback, but it turns out that:And that's why you can not expect any iterating functions working as usual on arrays created from
new Array(len)
.BTW, Safari and Firefox have a much better "printing" to this situation:
I have already submitted an issue to Chromium and ask them to fix this confusing printing:
https://bugs.chromium.org/p/chromium/issues/detail?id=732021
UPDATE: It's already fixed. Chrome now printed as:
奇怪的是,在 Chrome 中,
new Array(size)
几乎比[]
快 2 倍,在 FF 和 IE 中也差不多(通过创建和填充数组来衡量)。 仅当您知道数组的大致大小时才重要。 如果添加的项目多于给定的长度,性能提升就会丢失。更准确地说:
Array(
是一种快速恒定时间操作,不分配内存,而[]
是一种设置类型和值的线性时间操作。Oddly enough,
new Array(size)
is almost 2x faster than[]
in Chrome, and about the same in FF and IE (measured by creating and filling an array). It only matters if you know the approximate size of the array. If you add more items than the length you've given, the performance boost is lost.More accurately:
Array(
is a fast constant time operation that allocates no memory, wheras[]
is a linear time operation that sets type and value.有关详细信息,以下页面介绍了为什么你永远不需要使用 new Array()
另请查看注释 -
new Array(length)
形式没有任何有用的目的(至少在当今的 JavaScript 实现中)。For more information, the following page describes why you never need to use
new Array()
Also check out the comments - the
new Array(length)
form does not serve any useful purpose (at least in today's implementations of JavaScript).第一个是默认对象构造函数调用。 如果需要,您可以使用它的参数。
第二个使您能够创建非空数组:
The first one is the default object constructor call. You can use it's parameters if you want.
The second one gives you the ability to create not empty array:
为了更好地理解
[]
和new Array()
:以上结果来自Windows 7上的Google Chrome控制台。
In order to better understand
[]
andnew Array()
:The above result is from Google Chrome console on Windows 7.
我可以从这个基于 Fredrik 的好例子的示例开始,以更具体的方式进行解释。
我刚刚向数组添加了另一个值,并发出了四个警报:
第一个和第二个是给我们存储在每个数组中的值,以确保这些值。 他们将返回相同的!
现在尝试第三个,它返回 false,那是因为
第一个区别是,当我们调用 test1 时,它会不假思索地调用一个变量,它只返回存储在该变量中的值,而不管其数据类型!
但是,当我们调用 test2 时,它会调用 Array() 函数,然后将我们的 “Pushed” 值存储在其 “Value” 属性中,当我们警告 test2 时,也会发生同样的情况,它返回数组对象的“Value”属性。
因此,当我们检查 test1 是否等于 test2 时,它们当然永远不会返回 true,一个是函数,另一个是变量(具有数组类型),即使它们具有相同的值!
为了确定这一点,请尝试添加 .value 的第四个警报; 它会返回true。 在这种情况下,我们告诉 JS“无论容器的类型是函数还是变量,请比较每个容器中存储的值并告诉我们您看到了什么!” 这正是发生的情况。
我希望我清楚地表达了背后的想法,并为我糟糕的英语感到抱歉。
I can explain in a more specific way starting with this example that's based on Fredrik's good one.
I just added another value to the arrays, and made four alerts:
The first and second are to give us the value stored in each array, to be sure about the values. They will return the same!
Now try the third one, it returns false, that's because
The first difference is when we call test1 it calls a variable without thinking, it just returns the values that are stored in this variable disregarding its data type!
But, when we call test2 it calls the Array() function and then it stores our "Pushed" values in its "Value" property, and the same happens when we alert test2, it returns the "Value" property of the array object.
So when we check if test1 equals test2 of course they will never return true, one is a function and the other is a variable (with a type of array), even if they have the same value!
To be sure about that, try the 4th alert, with the .value added to it; it will return true. In this case we tell JS "Disregarding the type of the container, whether was it function or variable, please compare the values that are stored in each container and tell us what you've seen!" that's exactly what happens.
I hope I said the idea behind that clearly, and sorry for my bad English.
好吧,
var x = new Array()
与var x = []
在某些功能上有所不同,我将只解释最有用的两个(在我看来)其中。在我开始解释这些差异之前,我将首先设定一个基础; 当我们使用 x = [] 定义一个数据类型为 Array 的新变量时,它继承了属于数组原型的所有方法,这与扩展类非常相似(但不完全一样)。 然而,当我们使用 x = new Array() 时,它会初始化分配给变量 x 的数组原型的克隆。
现在让我们看看有什么区别
第一个区别是使用
new Array(x)
(其中x
是一个整数)初始化一个数组< code>x 未定义的值,例如new Array(16)
将初始化一个包含 16 个项目的数组,所有项目均未定义。 当您异步填充预定义长度的数组时,这非常有用。例如(再次:))假设您正在获取 100 个竞争对手的结果,并且您从远程系统或数据库异步接收它们,那么您需要在收到后根据排名在数组中分配它们每个结果。 在这种非常罕见的情况下,您将执行类似
myArray[result.rank - 1] = result.name
的操作,因此排名 1 将设置为索引 0,依此类推。第二个区别是,正如您所知,使用
new Array()
实例化数组原型的全新克隆并将其分配给您的变量,这允许您执行以下操作:一些魔法(顺便说一下,不推荐)。 这个神奇之处在于你可以覆盖遗留数组方法的特定方法。 因此,例如,您可以设置 Array.push 方法将新值推送到数组的开头而不是结尾,并且您还可以向此特定添加新方法(这样更好)数组原型的克隆。 这将允许您使用自己添加的方法在整个项目中定义更复杂的数组类型并将其用作类。最后一件事,如果您属于极少数关心应用程序的处理开销和内存消耗的人(我真正喜欢的人),那么您永远不会在不绝望的情况下接触
new Array()
用它 :)。我希望这已经足够解释了这个野兽
new Array()
:)Well,
var x = new Array()
is different thanvar x = []
is different in some features I'll just explain the most useful two (in my opinion) of them.Before I get into explaining the differences, I will set a base first; when we use
x = []
defines a new variable with data type of Array, and it inherits all the methods that belong to the array prototype, something pretty similar (but not exactly) to extending a class. However, when we usex = new Array()
it initilizes a clone of the array prototype assigned to the variablex
.Now let's see what are the difference
The First Difference is that using
new Array(x)
wherex
is an integer, initilizes an array ofx
undefined values, for examplenew Array(16)
will initialize an array with 16 items all of them are undefined. This is very useful when you asynchronously fill an array of a predefined length.For example (again :) ) let's say you are getting the results of 100 competitiors, and you're receiving them asynchronously from a remote system or db, then you'll need to allocate them in the array according to the rank once you receive each result. In this very rare case you will do something like
myArray[result.rank - 1] = result.name
, so the rank 1 will be set to the index 0 and so on.The second difference is that using
new Array()
as you already know, instanciates a whole new clone of the array prototype and assigns it to your variable, that allows you to do some magic (not recommended by the way). This magic is that you can overwrite a specific method of the legacy array methods. So, for example you can set theArray.push
method to push the new value to the beginning of the array instead of the end, and you can also add new methods (this is better) to this specific clone of the Array Prototype. That will allow you to define more complex types of arrays throughout your project with your own added methods and use it as a class.Last thing, if you're from the very few people (that I truly love) that care about processing overhead and memory consumption of your app, you'd never touch
new Array()
without being desperate to use it :).I hope that has explained enough about the beast
new Array()
:)当您初始化没有任何长度的数组时,没有任何区别。 所以
var a = []
&var b = new Array()
是一样的。但是如果你用
var b = new Array(1);
这样的长度初始化数组,它会将数组对象的长度设置为1。所以它相当于var b = []; b.length=1;
。每当您执行 array_object.push 时,这都会出现问题,它会在最后一个元素之后添加项目 & 增加长度。
与
There is no difference when you initialise array without any length. So
var a = []
&var b = new Array()
is same.But if you initialise array with length like
var b = new Array(1);
, it will set array object's length to 1. So its equivalent tovar b = []; b.length=1;
.This will be problematic whenever you do array_object.push, it add item after last element & increase length.
vs
这里面的内容远比表面上看到的还要多。 大多数其他答案都是正确的但也..
new Array(n)
n
元素重新分配空间<代码>[1,2,3]|| []
delete
或[1,,3]
语法)for ..
、forEach
、map
等)There's more to this than meets the eye. Most other answers are correct BUT ALSO..
new Array(n)
n
elements[1, 2, 3] || []
delete
or[1,,3]
syntax)for ..
,forEach
,map
, etc)第一个是默认的对象构造函数调用。主要用于动态值。
创建静态值时使用第二个数组
The first one is the default object constructor call.mostly used for dynamic values.
the second array is used when creating static values
的区别
使用Or
在这个问题中已经讨论得足够多了。
我想补充一下速度问题 - 当前最快的方法,在
google chrome
上是第二个。但请注意,这些事情往往会随着更新而发生很大变化。 此外,不同浏览器之间的运行时间也会有所不同。
例如 - 我提到的第二个选项在
chrome
上以 200 万次[操作/秒]运行,但如果您在mozilla dev.
上尝试它,您会获得了令人惊讶的更高的2300万的比率。无论如何,我建议您每隔一段时间在不同的浏览器(和机器)上使用网站 这样
The difference of using
Or
As been discussed enough in this question.
I would like to add the speed issue - the current fastest way, on
google chrome
is the second one.But pay attention, these things tend to change a lot with updates. Also the run time will differ between different browsers.
For example - the 2nd option that i mentioned, runs at 2 million [ops/second] on
chrome
, but if you'd try it onmozilla dev.
you'd get a surprisingly higher rate of 23 million.Anyway, I'd suggest you check it out, every once in a while, on different browsers (and machines), using site as such
据我所知,您可以找到切片(或数组的其他功能),例如code1。和code2显示您Array和他的< em>实例:
代码1:
代码2:
结论:
正如你所看到的
[]
和< code>new Array() 创建一个新的 Array 实例。它们都从Array.prototype
获取原型函数,它们只是 Array 的不同实例。所以这解释了为什么
[] != []
:)
As I know the diference u can find the slice(or the other funcitons of Array) like code1.and code2 show u Array and his instances:
code1:
code2:
conclusion:
as u can see
[]
andnew Array()
create a new instance of Array.And they all get the prototype functions fromArray.prototype
They are just different instance of Array.so this explain why
[] != []
:)
没有什么大的区别,它们基本上做同样的事情,但是以不同的方式做,但是请继续阅读,看看 W3C 的这个声明:
和
但与此同时,使用 new Array 语法创建新数组被认为是一种不好的做法:
所以基本上不被认为是最佳实践,也有一个细微的差别,你可以像这样将长度传递给 new Array(length) ,这也不是推荐的方式。
There is no big difference, they basically do the same thing but doing them in different ways, but read on, look at this statement at W3C:
and
But at the same time, creating new array using
new Array
syntax considered as a bad practice:So basically not considered as the best practice, also there is one minor difference there, you can pass length to
new Array(length)
like this, which also not a recommended way.我使用 [] 发生了奇怪的行为。
我们有模型“类”,其字段初始化为某个值。 例如:
我发现当字段用
[]
初始化时,它将被所有模型对象共享。 对其中一项的更改会影响所有其他项。使用 new Array() 初始化它们时不会发生这种情况。 对象的初始化也是如此(
{}
与 newObject()
)TBH 我不确定这是否是我们使用的框架的问题(Dojo)
I've incurred in a weird behaviour using [].
We have Model "classes" with fields initialised to some value. E.g.:
I found that when the fields are initialised with
[]
then it would be shared by all Model objects. Making changes to one affects all others.This doesn't happen initialising them with
new Array()
. Same for the initialisation of Objects ({}
vs newObject()
)TBH I am not sure if its a problem with the framework we were using (Dojo)
我在使用 Promise 时发现了差异。 在使用 Promise 数组(比如 arr,初始化为 arr=[])时,在 Promise.all(arr) 中出现错误。 而当声明为 arr = Array() 时,没有出现编译问题。 希望这可以帮助。
I found a difference while using promises. While using array of promises (say arr, initialised as arr=[]), got an error in Promise.all(arr). Whereas when declared as arr = Array(), did not get compilation issues. Hope this helps.
请记住:
使用 new 或跳过它,不会对代码的功能产生影响。
考虑这个例子:
使用理由:
不使用的原因:新
- 避免额外的编码,因为有时代码几乎成为同义词。
希望能帮助到你。
Keep in mind:
Work with new or skip it, there will be no effect on the functioning of the code.
Consider this example:
Reasons to Use: New
Reason not to use: New
-Avoid the extra coding, as sometimes code becomes virtually synonymous.
Hope it helps.
我发现这两种结构之间的一个差异让我很痛苦。
假设我有:
在现实生活中,如果我这样做:
我最终得到的是这样的:
我不知道语言规范所说的应该发生什么,但是如果我希望我的两个对象在我的对象,我必须使用
new Array()
。I've found one difference between the two constructions that bit me pretty hard.
Let's say I have:
In real life, if I do this:
What I end up with is this:
I don't know what the language specification says is supposed to happen, but if I want my two objects to have unique property arrays in my objects, I have to use
new Array()
.使用 Array 构造函数创建一个所需长度的新数组,并用未定义的值填充每个索引,将数组分配给变量 one 会创建您为其提供信息的索引。
Using the Array constructor makes a new array of the desired length and populates each of the indices with undefined, the assigned an array to a variable one creates the indices that you give it info for.
有区别,但在该示例中没有区别。
使用更详细的方法:
new Array()
在参数中确实有一个额外的选项:如果将一个数字传递给构造函数,您将获得一个该长度的数组:为了说明不同的方法创建数组:
另一个区别是,使用 new Array() 时,您可以设置数组的大小,这会影响堆栈大小。 如果您遇到堆栈溢出(Array.push 与 Array.unshift 的性能)(发生这种情况),这可能会很有用当数组的大小超过堆栈的大小时,必须重新创建数组。 因此,根据用例,使用 new Array() 时实际上可以提高性能,因为可以防止溢出的发生。
正如这个答案中指出的,
new Array(5)
实际上不会添加五个未定义
项添加到数组中。 它只是增加了五个项目的空间。 请注意,以这种方式使用Array
会使依赖array.length
进行计算变得困难。There is a difference, but there is no difference in that example.
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:To illustrate the different ways to create an 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 usingnew Array()
because you can prevent the overflow from happening.As pointed out in this answer,
new Array(5)
will not actually add fiveundefined
items to the array. It simply adds space for five items. Be aware that usingArray
this way makes it difficult to rely onarray.length
for calculations.