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

后端 未结 7 645
轻奢々
轻奢々 2020-12-05 10:49

What are the advantages of using

var foo = []; 

over using

var bar = new Array();

i\'ve been told to use

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 11:18

    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.

提交回复
热议问题