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

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

    Both are correct only. But most of the people use var a = []

    Three Ways to Declare an Array in JavaScript.

    method 1: We can explicitly declare an array with the JavaScript "new" keyword to instantiate the array in memory (i.e. create it, and make it available).

    // Declare an array (using the array constructor)
    var arlene1 = new Array();
    var arlene2 = new Array("First element", "Second", "Last");
    

    method 2: we use an alternate method to declaring arrays.

    // Declare an array (using literal notation)
    var arlene1 = [];
    var arlene2 = ["First element", "Second", "Last"];
    

    method 3: JavaScript also lets you create arrays indirectly, by calling specific methods.

    // Create an array from a method's return value
    var carter = "I-learn-JavaScript";
    var arlene3 = carter.split("-");
    

提交回复
热议问题