任何人都可以请解释第一个例子和第二个例子有什么区别吗?声明的“未定义”值和未声明的“未定义”值之间有什么区别?
声明的“未定义”值和未声明的“未定义”值之间有什么区别?
代码
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