任何人都可以請解釋第一個例子和第二個例子有什麼區別嗎?聲明的「未定義」值和未聲明的「未定義」值之間有什麼區別?
聲明的「未定義」值和未聲明的「未定義」值之間有什麼區別?
代碼
var arr = new Array(4);
arr[0] = "a";
arr[1] = "b";
arr[2] = undefined; //insert undefined here!
arr[3] = "d";
console.log("arr[2] is " + arr[2]); //yes, it is undefined!
arr.forEach(function(value, index) {
console.log(index + ":" + value);
})
console.log("====================")
var arr = new Array(4);
arr[0] = "a";
arr[1] = "b";
//I don't insert undefined to arr[2] in this case.
arr[3] = "d";
console.log("arr[2] is " + arr[2]); //yes, it is undefined!
arr.forEach(function(value, index) {
console.log(index + ":" + value);
})
登錄
arr[2] is undefined
0:a
1:b
2:undefined
3:d
====================
arr[2] is undefined
0:a
1:b
3:d
附加實施例
var arr = new Array(4);
arr[0] = "a";
arr[1] = "b";
arr[2] = undefined; //insert undefined here!
arr[3] = "d";
console.log("arr[2] is " + arr[2]); //yes, it is undefined!
var i = 0;
var max = arr.length;
for(i; i < max; i++) {
console.log(i + ":" + arr[i]);
}
console.log("====================")
var arr = new Array(4);
arr[0] = "a";
arr[1] = "b";
//I don't insert undefined to arr[2] in this case.
arr[3] = "d";
console.log("arr[2] is " + arr[2]); //yes, it is undefined!
var i = 0;
var max = arr.length;
for(i; i < max; i++) {
console.log(i + ":" + arr[i]);
}
日誌
arr[2] is undefined
0:a
1:b
2:undefined
3:d
====================
arr[2] is undefined
0:a
1:b
2:undefined
3:d
一個被初始化(在JS中我們說'聲明')但未定義;一個是不初始化和undefined – jeremy
可能重複[是JavaScript數組稀疏?](http://stackoverflow.com/questions/1510778/are-javascript-arys-sparse) – Ramanlfc
@Ramanlfc這不是重複的那個問題。 OP很清楚這方面的內容 – jeremy