谁能解释一下第一个示例和第二个示例之间的区别是什么?
声明的“未定义”值和未声明的“未定义”值有什么区别?
代码
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
最佳答案
在第一个例子中:
var arr = new Array(4);
创建一个长度为 4 的数组,它没有元素。
然后使用直接赋值为索引 0 到 3 赋值:
arr[0] = "a";
arr[1] = "b";
arr[2] = undefined; //insert undefined here!
arr[3] = "d";
它创建属性 0 到 3。 undefined 被分配给
arr[2]
。 forEach 迭代存在的元素,因此您可以看到所有 4 个元素的结果,每个元素都有一个值。在第二个示例中,您没有为
arr[2]
赋值。当访问对象的不存在属性时(注意数组是对象),返回未定义的值,例如var obj = {};
console.log(obj.foo) // undefined
使用 forEach 循环遍历属性时,不会访问不存在的属性,因此
arr[2]
没有输出。这与 for 循环相反,for 循环通常被编写为访问从 0 到 length - 1
的所有属性,因此返回该范围内所有属性的值,无论它们是否存在。关于javascript - 已声明的 "undefined"值和未声明的 "undefined"值有什么区别?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37781608/