gpt4 book ai didi

javascript - 声明的 "undefined"值和未声明的 "undefined"值有什么区别?

转载 作者:行者123 更新时间:2023-11-29 14:41:32 25 4
gpt4 key购买 nike

谁能解释一下第一个例子和第二个例子有什么区别?

声明的“未定义”值和未声明的“未定义”值有什么区别?

代码

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

最佳答案

Could anyone please explain what's the difference between the first example and the second example, please?

在第一个例子中:

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]赋值。当访问一个对象的不存在的属性时(注意数组是对象),undefined 值被返回,例如

var obj = {};
console.log(obj.foo) // undefined

当使用 forEach 遍历属性时,不访问不存在的属性,因此 arr[2] 没有输出。这与 for 循环相反,后者通常用于访问从 0 到 length - 1 的所有属性,因此返回该范围内所有属性的值,无论它们是否存在还是不是。

关于javascript - 声明的 "undefined"值和未声明的 "undefined"值有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37781608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com