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

后端 未结 18 1470
生来不讨喜
生来不讨喜 2020-11-21 12:00

What\'s the real difference between declaring an array like this:

var myArray = new Array();

and

var myArray = [];
<         


        
18条回答
  •  广开言路
    2020-11-21 12:47

    There is no big difference, they basically do the same thing but doing them in different ways, but read on, look at this statement at W3C:

    var cars = ["Saab", "Volvo","BMW"];
    

    and

    var cars = new Array("Saab", "Volvo", "BMW");
    

    The two examples above do exactly the same. There is no need to use new Array().
    For simplicity, readability and execution speed, use the first one (the array literal method).

    But at the same time, creating new array using new Array syntax considered as a bad practice:

    Avoid new Array()

    There is no need to use the JavaScript's built-in array constructor new Array().
    Use [] instead.
    These two different statements both create a new empty array named points:

    var points = new Array();         // Bad
    var points = [];                  // Good 
    

    These two different statements both create a new array containing 6 numbers:

    var points = new Array(40, 100, 1, 5, 25, 10); // Bad    
    var points = [40, 100, 1, 5, 25, 10];          // Good
    

    The new keyword only complicates the code. It can also produce some unexpected results:

    var points = new Array(40, 100);  // Creates an array with two elements (40 and 100)
    

    What if I remove one of the elements?

    var points = new Array(40);       // Creates an array with 40 undefined elements !!!!!
    

    So basically not considered as the best practice, also there is one minor difference there, you can pass length to new Array(length) like this, which also not a recommended way.

提交回复
热议问题