在javascript中定义数组 [英] defining array in javascript
本文介绍了在javascript中定义数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 javascript 中创建一个数组并记住两种方法,所以我只想知道根本区别是什么,以及这两种样式"是否存在性能差异
I want to create an array in javascript and remember two ways of doing it so I just want to know what the fundamental differences are and if there is a performance difference in these two "styles"
var array_1 = new Array("fee","fie","foo","fum");
var array_2 = ['a','b','c'];
for (let i=0; i<array_1.length; i++){
console.log(array_1[i])
}
for (let i=0; i<array_2.length; i++){
console.log(array_2[i])
}
推荐答案
他们做同样的事情.[]
符号的优点是:
They do the same thing. Advantages to the []
notation are:
- 它更短.
- 如果有人做了一些愚蠢的事情,比如重新定义
Array
符号,它仍然有效. - 当您只定义一个条目时没有歧义,而当您编写
new Array(3)
时,如果您习惯于看到在构造函数中列出的条目,您很容易将其误读为意味着[3]
,实际上它创建了一个length
为 3 且没有条目的新数组. - 它可能会更快一点点(取决于 JavaScript 实现),因为当你说
new Array
时,解释器必须去查找Array
符号,这意味着遍历作用域链中的所有条目,直到它到达全局对象并找到它,而使用[]
则不需要这样做.在正常用例中产生任何实际现实世界影响的可能性很低.尽管如此……
- It's shorter.
- If someone does something silly like redefine the
Array
symbol, it still works. - There's no ambiguity when you only define a single entry, whereas when you write
new Array(3)
, if you're used to seeing entries listed in the constructor, you could easily misread that to mean[3]
, when in fact it creates a new array with alength
of 3 and no entries. - It may be a tiny little bit faster (depending on JavaScript implementation), because when you say
new Array
, the interpreter has to go look up theArray
symbol, which means traversing all entries in the scope chain until it gets to the global object and finds it, whereas with[]
it doesn't need to do that. The odds of that having any tangible real-world impact in normal use cases are low. Still, though...
所以使用[]
有几个很好的理由.
So there are several good reasons to use []
.
新数组
的优势:
- 可以设置数组的初始长度,例如,
var a = new Array(3);
几年来我没有任何理由这样做(自从得知 数组并不是真正的数组,并且尝试预先分配它们是没有意义的).如果你真的想要,你可以随时这样做:
I haven't had any reason to do that in several years (not since learning that arrays aren't really arrays and there's no point trying to pre-allocate them). And if you really want to, you can always do this:
var a = [];
a.length = 3;
这篇关于在javascript中定义数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文