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

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

提交回复
热议问题