16.迭代器自定义遍历数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
const className = {
name: "三年一班",
students: ["小明", "小花", "小亮", "小王", "小李"],
[Symbol.iterator]() {
// 创建索引值
let index = 0;
// 保存this
let that = this;
return {
next: function () {
//这里也可以直接写今天函数,没有this指向问题
if (index < that.students.length) {
const result = { value: that.students[index], done: false };
// 索引值自增
index++;
return result;
} else {
return { value: undefined, done: true };
}
},
};
},
};
// for (const iterator of className.studets) {
// console.log(iterator);
// }
for (const v of className) {
console.log(v);
}
</script>
</body>
</html>