What are the best practices to follow when declaring an array in Javascript?

后端 未结 9 1086
闹比i
闹比i 2020-11-28 02:11

When I need to declare a new array I use this notation

var arr = new Array();

But when testing online, for example on jsbin, a warning sign

相关标签:
9条回答
  • 2020-11-28 02:48

    One significant difference is that [] will always instantiate a new Array, whereas new Array could be hijacked to create a different object.

    (function () {
        "use strict";
        var foo,
            bar;
        //don't do this, it's a bad idea
        function Array() {
            alert('foo');
        }
        foo = new Array();
        bar = [];
    }());​
    

    In my example code, I've kept the Array function hidden from the rest of the document scope, however it's more likely that if you ever run into this sort of issue that the code won't have been left in a nice closure, and will likely be difficult to locate.

    Disclaimer: It's not a good idea to hijack the Array constructor.

    0 讨论(0)
  • 2020-11-28 02:49
    • var arr=[] uses the array/object literal
    • var arr = new Array() use the array/object constructor

    The speediest way to define an array or object is literal way, because you don't need to call the constructor

    var arr1 = new Array(1, 2, 3, 4);
    var arr2 = [1, 2, 3, 4];
    
    alert(arr1[0]); // 1
    alert(arr2[0]); // 1
    
    var arr3 = new Array(200);
    var arr4 = [200];
    
    alert(arr3[0]); // 'undefined'
    alert(arr4[0]); // 200
    
    0 讨论(0)
  • 2020-11-28 02:54

    It's because new Array() is ambiguous. These are the correct constructors:

    // Using brackets
    [element0, element1, ..., elementN]
    
    // Using new AND a list of elements
    new Array(element0, element1, ..., elementN)
    
    // Using new AND an integer specifying the array length
    new Array(arrayLength)
    
    0 讨论(0)
提交回复
热议问题