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

后端 未结 9 1132
闹比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.

提交回复
热议问题