2012-08-04 312 views
8

可能重複:
What is 「undefined x 1」 in JavaScript? [undefined]和[,]之間的區別是什麼?

在鉻21,餵養[,]到控制檯輸出

[未定義X 1]

和饋送[undefined]輸出

[未定義]

是什麼[undefined][undefined x 1]之間的差異?

什麼是符號[undefined x 1]

+4

我相信,你需要閱讀此[鏈接](http://stackoverflow.com/questions/10683773/what-is-undefined-x-1-in-javascript) – 2012-08-04 13:15:28

+0

'[]'變我'[]'... – pimvdb 2012-08-04 13:15:58

+2

控制檯輸出不是數據,它不是*(必然)* JavaScript表示法或語法。這是控制檯開發人員認爲應該看起來的數據的可視化表示。有時這很有幫助,有時可能會造成混淆或誤導。 – 2012-08-04 13:21:21

回答

11

[,]sparse array。它的長度爲1,但沒有值(0 in [,] === false)。它也可以寫成new Array(1)

[undefined]是長度爲1的數組,其值爲undefined,索引號爲0

訪問屬性「0」時,兩者都會返回undefined - 第一個因爲該屬性未定義,第二個因爲值爲「未定義」。但是,陣列不同,它們的output in the console也是不同的。

-1

看起來它只是顯示重複'未定義'值的簡寫方式。例如:

> [,,,] 
    [ undefined x 3 ] 

[]是不一樣的[undefined]可言。如果我是你,我會仔細檢查一下。

+0

請重新閱讀我的問題。我問'','',而不是'[]'。 – Randomblue 2012-08-04 13:17:59

+0

pimvdb的編輯說明:http://es5.github.com/#x11.1.4,「如果一個元素在數組末尾消失,那麼該元素不會影響數組的長度。」 – 2012-08-04 13:20:55

+0

@Randomblue很好,因爲你編輯它..: - \ – nickf 2012-08-04 13:43:49

0

那奇[]輸出只是[]再次爲我在Chrome 21

反正[a, b, c, ...]是的JavaScript數組符號,所以你基本上是定義沒有值的數組。

然而結尾,是可以接受的,使數組產生更容易。那麼Chrome告訴你的是陣列中有一個未定義的值。查看代碼示例。

[,,] 
> [undefined x2] 
[1,2,] 
> [1, 2] 
[1,2,,] 
> [1, 2, undefined × 1] 
[1,2,,,] 
> [1, 2, undefined × 2] 
[1,2,,3,4,,,6] 
> [1, 2, undefined × 1, 3, 4, undefined × 2, 6] 
+1

值不確定,因爲它們不存在;它們沒有設置爲「未定義」。 JavaScript可以完美地處理這樣的數組。 – pimvdb 2012-08-04 13:26:46

+0

這是undefined的定義。究竟是什麼問題? – dualed 2012-08-04 13:31:15

+0

問題是不太準確的措辭。如果你不介意,我編輯過。 – pimvdb 2012-08-04 13:32:59

5

[,]創建長度爲1且沒有索引的數組。

[undefined]創建長度爲1的數組,undefined值爲索引0

Chrome的undefined × x是稀疏數組沒有循序索引:

var a = []; 

a[8] = void 0; //set the 8th index to undefined, this will make the array's length to be 9 as specified. The array is sparse 
console.log(a) //Logs undefined × 8, undefined, which means there are 8 missing indices and then a value `undefined` 

如果你是一個稀疏陣列上使用.forEach,它跳過不存在的指標。

a.forEach(function() { 
    console.log(true); //Only logs one true even though the array's length is 9 
}); 

哪裏,如果你做一個正常的.length基於循環:

for (var i = 0; i < a.length; ++i) { 
    console.log(true); //will of course log 9 times because it's only .length based 
} 

有一種疑難雜症,如果你希望.forEach有同樣的表現非標準實現。

new Array(50).forEach(function() { 
    //Not called, the array doesn't have any indices 
}); 

$.each(new Array(50), function() { 
    //Typical custom implementation calls this 50 times 
}); 
相關問題