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

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

提交回复
热议问题