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

后端 未结 18 1373
生来不讨喜
生来不讨喜 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.

    0 讨论(0)
  • 2020-11-21 12:49

    In order to better understand [] and new Array():

    > []
      []
    > new Array()
      []
    > [] == []
      false
    > [] === []
      false
    > new Array() == new Array()
      false
    > new Array() === new Array()
      false
    > typeof ([])
      "object"
    > typeof (new Array())
      "object"
    > [] === new Array()
      false
    > [] == new Array()
      false
    

    The above result is from Google Chrome console on Windows 7.

    0 讨论(0)
  • 2020-11-21 12:50

    The difference between creating an array with the implicit array and the array constructor is subtle but important.

    When you create an array using

    var a = [];
    

    You're telling the interpreter to create a new runtime array. No extra processing necessary at all. Done.

    If you use:

    var a = new Array();
    

    You're telling the interpreter, I want to call the constructor "Array" and generate an object. It then looks up through your execution context to find the constructor to call, and calls it, creating your array.

    You may think "Well, this doesn't matter at all. They're the same!". Unfortunately you can't guarantee that.

    Take the following example:

    function Array() {
        this.is = 'SPARTA';
    }
    
    var a = new Array();
    var b = [];
    
    alert(a.is);  // => 'SPARTA'
    alert(b.is);  // => undefined
    a.push('Woa'); // => TypeError: a.push is not a function
    b.push('Woa'); // => 1 (OK)
    

    In the above example, the first call will alert 'SPARTA' as you'd expect. The second will not. You will end up seeing undefined. You'll also note that b contains all of the native Array object functions such as push, where the other does not.

    While you may expect this to happen, it just illustrates the fact that [] is not the same as new Array().

    It's probably best to just use [] if you know you just want an array. I also do not suggest going around and redefining Array...

    0 讨论(0)
  • 2020-11-21 12:53

    For more information, the following page describes why you never need to use new Array()

    You never need to use new Object() in JavaScript. Use the object literal {} instead. Similarly, don’t use new Array(), use the array literal [] instead. Arrays in JavaScript work nothing like the arrays in Java, and use of the Java-like syntax will confuse you.

    Do not use new Number, new String, or new Boolean. These forms produce unnecessary object wrappers. Just use simple literals instead.

    Also check out the comments - the new Array(length) form does not serve any useful purpose (at least in today's implementations of JavaScript).

    0 讨论(0)
  • 2020-11-21 12:54

    There is a difference, but there is no difference in that example.

    Using the more verbose method: new Array() does have one extra option in the parameters: if you pass a number to the constructor, you will get an array of that length:

    x = new Array(5);
    alert(x.length); // 5
    

    To illustrate the different ways to create an array:

    var a = [],            // these are the same
        b = new Array(),   // a and b are arrays with length 0
    
        c = ['foo', 'bar'],           // these are the same
        d = new Array('foo', 'bar'),  // c and d are arrays with 2 strings
    
        // these are different:
        e = [3]             // e.length == 1, e[0] == 3
        f = new Array(3),   // f.length == 3, f[0] == undefined
    
    ;
    

    Another difference is that when using new Array() you're able to set the size of the array, which affects the stack size. This can be useful if you're getting stack overflows (Performance of Array.push vs Array.unshift) which is what happens when the size of the array exceeds the size of the stack, and it has to be re-created. So there can actually, depending on the use case, be a performance increase when using new Array() because you can prevent the overflow from happening.

    As pointed out in this answer, new Array(5) will not actually add five undefined items to the array. It simply adds space for five items. Be aware that using Array this way makes it difficult to rely on array.length for calculations.

    0 讨论(0)
  • 2020-11-21 12:54

    Oddly enough, new Array(size) is almost 2x faster than [] in Chrome, and about the same in FF and IE (measured by creating and filling an array). It only matters if you know the approximate size of the array. If you add more items than the length you've given, the performance boost is lost.

    More accurately: Array( is a fast constant time operation that allocates no memory, wheras [] is a linear time operation that sets type and value.

    0 讨论(0)
提交回复
热议问题