开发者

What is the difference between Array() and [] in Javascript and why would I use one over the other? [duplicate]

This question already has answers here: 开发者_运维知识库 Closed 12 years ago.

Possible Duplicate:

What’s the difference between “Array()” and “[]” while declaring a JavaScript array?

In JavaScript you can create a new array like:

var arr = new Array();

or like:

var arr2 = [];

What is the difference and why would you do one over the other?


new Array(2) proudces an array of size 2, containing two undefineds. [2] produces an array of size 1, containing number 2. new Array IMO doesn't fit with the spirit of JavaScript, even though it may make array construction much more findable. That may or may not be of any importance (I use literals almost exclusively in JavaScript for all applicable types, and I've authored/maintained large pieces of JavaScript [30-50 KLOC] successfully).

edit I guess the reasons seasoned javascript programmers avoid new Array syntax are:

  • it doesn't behave uniformly across argument numbers and types ((new Array(X)).length == 1 for any X as long as typeof(X) != "number"
  • it's more verbose and the only thing you gain is the irregularity


Another (minor) reason to use [] in preference to new Array() is that Array could potentially be overridden (though I've never seen it happen) and [] is guaranteed to work.

Array = "something";
var a = new Array(); // Fails
var b = []; // Works


I believe they're identical. I never use new Array();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜