为什么无法全部遍历打印
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const obj = {
"0": "xm",
"sex": "male",
length: 2
}
// 在此补充代码
obj[Symbol.iterator]=Array.prototype[Symbol.iterator];
for(const i of obj){
console.log(i)
}
</script>
</body>
</html>问题描述:
为什么无法全部遍历打印,问题在哪?
8
收起
正在回答
1回答
同学你好,遍历的是有索引的,例如数组:

而对象中的属性名为数字的只有第一个0,所以只输出xm;不是数字的,会返回undefined值,并且length不会输出。
建议参考课程中的写法:

修改为:
const obj = {
"0": "xm",
"sex": "male",
length: 2
};
// 在此补充代码
// obj[Symbol.iterator] = Array.prototype[Symbol.iterator];
obj[Symbol.iterator] = () => {
let index = 0;
return {
next() {
index++;
if (index === 1) {
return {
value: obj["0"],
done: false,
};
} else if (index === 2) {
return {
value: obj["sex"],
done: false,
};
} else if (index === 3) {
return {
value: obj["length"],
};
} else {
return {
done: true,
};
}
},
};
};
for (const i of obj) {
console.log(i);
}祝学习愉快!


恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星