在JavaScript中,为什么[]比新的Array()更受欢迎;? [英] In JavaScript, why is [ ] preferred over new Array();?
问题描述
我记得在某处读过(我认为这是在Crockford的一篇论文中)使用数组文字 []
比使用更新Array();
表示法。
但我真的不记得一个优于另一个的优点。
有人可以向我解释为什么前者比后者更受欢迎吗?
这是我能想到的原因之一 []
优于 new Array();
:
var Array = function(){};
覆盖数组
对象将破坏代码。 ..!
更多理由?
简洁 h2>
它通过网络传输的字节数更少,要解释的字节数更少,解析它的心理资源更少。
少即是多。
一致性
这两行代码有什么区别?
var arr = [5];
var arr = new Array(5);
根据这里 new Array(5);
不会返回一个包含5的数组,而是返回一个5元素数组,所有元素都是 undefined
。而这两行返回相同的数组。
var arr = [5,6];
var arr = new Array(5,6);
I remember reading somewhere (I think it was in one of Crockford's papers) that using an array literal []
is better than using the new Array();
notation.
But I can't really remember any advantages of one over the other.
Can anyone please explain to me on why the former is preferred over the latter?
Here is one reason I can think of on why []
is better than new Array();
:
var Array = function () { };
Overriding the Array
object will break code...!
Any more reasons?
Brevity
It has less bytes to transfer over the wire, less bytes to interpret, less mental resources to parse it.
Less is more.
Consistency
What is the difference between these two lines of code?
var arr = [5];
var arr = new Array(5);
According to here new Array(5);
will not return an array with a 5 in it, instead it will return a 5 element array, with all the elements being undefined
. Whereas these two lines return identical arrays.
var arr = [5,6];
var arr = new Array(5,6);
这篇关于在JavaScript中,为什么[]比新的Array()更受欢迎;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!