第 11 屆 iT 邦幫忙鐵人賽

DAY 18
Modern Web

從Stack Overflow學前端系列 第 18


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

What's the real difference between declaring an array like this:

var myArray = new Array();


var myArray = [];

There is a difference, but there is no difference in that example.

Using the more verbose method: new Array() does have one extra option in the parameters: if you pass a number to the constructor, you will get an array of that length:
如果用比較詳盡的方式:new Array()的確有一個多出的參數的選項:如果你對一個建構子傳入數字,你會得到一個那個陣列的長度

x = new Array(5);
alert(x.length); // 5
To illustrate the different ways to create an array:

var a = [],            // these are the same
    b = new Array(),   // a and b are arrays with length 0

    c = ['foo', 'bar'],           // these are the same
    d = new Array('foo', 'bar'),  // c and d are arrays with 2 strings

    // these are different:
    e = [3]             // e.length == 1, e[0] == 3
    f = new Array(3),   // f.length == 3, f[0] == undefined

Another difference is that when using new Array() you're able to set the size of the array, which affects the stack size. This can be useful if you're getting stack overflows (Performance of Array.push vs Array.unshift) which is what happens when the size of the array exceeds the size of the stack, and it has to be re-created. So there can actually, depending on the use case, be a performance increase when using new Array() because you can prevent the overflow from happening.

As pointed out in this answer, new Array(5) will not actually add five undefined items to the array. It simply adds space for five items. Be aware that using Array this way makes it difficult to rely on array.length for calculations

另一個差異是,在用new Array()時,可以設定陣列長度,從而影響堆疊大小,這在你想讓堆疊溢出時特別有用(Array.push vs Array.unshift的效能),通常發生在陣列大小超過堆疊大小的時候,而且其必須是被重新創造的,所以根據應用場景不同,因為可以防止溢出的情況,用new Array()的效能會有所增長

new Array(5)其實並不會真的加入5個undefined項目進去陣列,而是加入空白的五個項目,注意這樣使用陣列會讓這個陣列比較難計算長度

從StackOverflow上學CODING(19) JS: console.log內的文字顏色
從Stack Overflow學前端30