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

后端 未结 9 1134
闹比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:38

    for maintainability, use []

    The array literal is more predictable, as most developers use it. Most array usage out there will be using the literal, and there is value in having your code match up with what other developers use.

    for empty arrays, use []

    var ns = [];
    var names = [ 'john', 'brian' ];
    

    As shown here, using the literal for empty and a couple of known elements is fatster than the Array constructor.

    for an array of known size, use new Array(size)

    If the size is known, then using the Array constructor significantly improves performance. However it also means you have to deal with an array which already has 'undefined' filling all it's values.

    As shown here

    // fill an array with 100 numbers
    var ns = new Array( 100 );
    for ( var i = 0; i < 100; i++ ) {
        ns[i] = i;
    }
    

    This also works for very small arrays too.

提交回复
热议问题