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

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

    There is no difference when you initialise array without any length. So var a = [] & var b = new Array() is same.

    But if you initialise array with length like var b = new Array(1);, it will set array object's length to 1. So its equivalent to var b = []; b.length=1;.

    This will be problematic whenever you do array_object.push, it add item after last element & increase length.

    var b = new Array(1);
    b.push("hello world");
    console.log(b.length); // print 2
    

    vs

    var v = [];
    a.push("hello world");
    console.log(b.length); // print 1
    
    0 讨论(0)
  • 2020-11-21 12:55

    The first one is the default object constructor call.mostly used for dynamic values.

    var array = new Array(length); //initialize with default length
    

    the second array is used when creating static values

    var array = [red, green, blue, yellow, white]; // this array will contain values.
    
    0 讨论(0)
  • 2020-11-21 12:56

    There's more to this than meets the eye. Most other answers are correct BUT ALSO..

    new Array(n)

    • Allows engine to reallocates space for n elements
    • Optimized for array creation
    • Created array is marked sparse which has the least performant array operations, that's because each index access has to check bounds, see if value exists and walk the prototype chain
    • If array is marked as sparse, there's no way back (at least in V8), it'll always be slower during its lifetime, even if you fill it up with content (packed array) 1ms or 2 hours later, doesn't matter

    [1, 2, 3] || []

    • Created array is marked packed (unless you use delete or [1,,3] syntax)
    • Optimized for array operations (for .., forEach, map, etc)
    • Engine needs to reallocate space as the array grows

    This probably isn't the case for older browser versions/browsers.

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

    There is an important difference that no answer has mentioned yet.

    From this:

    new Array(2).length           // 2
    new Array(2)[0] === undefined // true
    new Array(2)[1] === undefined // true
    

    You might think the new Array(2) is equivalent to [undefined, undefined], but it's NOT!

    Let's try with map():

    [undefined, undefined].map(e => 1)  // [1, 1]
    new Array(2).map(e => 1)            // "(2) [undefined × 2]" in Chrome
    

    See? The semantics are totally different! So why is that?

    According to ES6 Spec 22.1.1.2, the job of Array(len) is just creating a new array whose property length is set to the argument len and that's it, meaning there isn't any real element inside this newly created array.

    Function map(), according to spec 22.1.3.15 would firstly check HasProperty then call the callback, but it turns out that:

    new Array(2).hasOwnProperty(0) // false
    [undefined, undefined].hasOwnProperty(0) // true
    

    And that's why you can not expect any iterating functions working as usual on arrays created from new Array(len).

    BTW, Safari and Firefox have a much better "printing" to this situation:

    // Safari
    new Array(2)             // [](2)
    new Array(2).map(e => 1) // [](2) 
    [undefined, undefined]   // [undefined, undefined] (2) 
    
    // Firefox
    new Array(2)             // Array [ <2 empty slots> ]
    new Array(2).map(e => 1) // Array [ <2 empty slots> ]
    [undefined, undefined]   // Array [ undefined, undefined ]
    

    I have already submitted an issue to Chromium and ask them to fix this confusing printing: https://bugs.chromium.org/p/chromium/issues/detail?id=732021

    UPDATE: It's already fixed. Chrome now printed as:

    new Array(2)             // (2) [empty × 2]
    
    0 讨论(0)
  • 2020-11-21 12:57

    The difference of using

    var arr = new Array(size);
    

    Or

    arr = [];
    arr.length = size;
    

    As been discussed enough in this question.

    I would like to add the speed issue - the current fastest way, on google chrome is the second one.

    But pay attention, these things tend to change a lot with updates. Also the run time will differ between different browsers.

    For example - the 2nd option that i mentioned, runs at 2 million [ops/second] on chrome, but if you'd try it on mozilla dev. you'd get a surprisingly higher rate of 23 million.

    Anyway, I'd suggest you check it out, every once in a while, on different browsers (and machines), using site as such

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

    I've found one difference between the two constructions that bit me pretty hard.

    Let's say I have:

    function MyClass(){
      this.property1=[];
      this.property2=new Array();
    };
    var MyObject1=new MyClass();
    var MyObject2=new MyClass();
    

    In real life, if I do this:

    MyObject1.property1.push('a');
    MyObject1.property2.push('b');
    MyObject2.property1.push('c');
    MyObject2.property2.push('d');
    

    What I end up with is this:

    MyObject1.property1=['a','c']
    MyObject1.property2=['b']
    MyObject2.property1=['a','c']
    MyObject2.property2=['d']
    

    I don't know what the language specification says is supposed to happen, but if I want my two objects to have unique property arrays in my objects, I have to use new Array().

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