开发者

Advantages of using [] over new Array() in JavaScript

开发者 https://www.devze.com 2022-12-24 12:02 出处:网络
What are the advantages of using var foo = []; over usi开发者_如何学JAVAng var bar = new Array();

What are the advantages of using

var foo = []; 

over usi开发者_如何学JAVAng

var bar = new Array();

i've been told to use [] over new Array() but never with much explanation


The main reason to use [] as opposed to new Array() is the arguments you pass. When you use new Array(10), you create an empty array with 10 elements, but when you use [10], you create an array with one element who's value is 10. Since this is generally the information most programmers want to pass to an array (as arrays are dynamic in Javascript), this is generally considered the best practice. Also new Array(10,20) works differently than new Array(10). In this case you have the same effect as [10,20] which is to create an array with 2 elements, 10 and 20. Since this is... strange at best... it's easy to accidentally create an empty array by passing new Array() only one value. [] always has the same effect, so I'd also recommend sticking with it.


  • shorter
  • arguments of Array are confusing (e.g. new Array(10) and new Array("10") are quite different)


Both can be used as good. This discussion/confusion has started since Javascript guru Douglas Crockford told that the new keyword is considered harmful. Since then it was considered "good practice/technique" to leave out the new keyword to avoid unexpected results/behaviour. Also see this Stackoverflow topic.


Three reasons (the first two expanded upon in other answers):

  1. Shorter;
  2. Allows creation of arrays with one element, as detailed in Chibu's answer;
  3. Works even in the unlikely event of the Array constructor having been overwritten.

Non-reasons:

  1. Avoidance of the new operator. Don't be afraid of new just because Douglas Crockford was once bitten by it. It's extremely useful.


It scores you less symbols in code golf.


It's the same thing. The only reason to use [] over new Array() is that it's shorter.


shorter and cleaner. Should use {} to create objects as well.

0

精彩评论

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