迭代器的应用(遍历对象中的数组)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
// 声明一个对象
const banji = {
name:"一班",
stus:[
'小王',
'小名',
'小红'
],
// 加接口
// Uncaught TypeError: Result of the Symbol.iterator method is not an object
[Symbol.iterator](){
// 索引变量
let index=0;
let this1 = this;
return{
next:function(){
if(index<this1.stus.length){
const result = {value:this1.stus[index],done:false};
// 下标递增
index++;
return result;
}else{
// ture遍历完成
return {value:undefined,done:ture};
}
}
}
}
}

// 想要遍历这个对象的数组
for(let v of banji){
// Uncaught TypeError: banji is not iterable 报错
console.log(v);
}






// 不符合面向对象的思想
// banji.stus.forEach()
</script>
</body>
</html>

posted @ 2020-08-11 11:25  Smile*^  阅读(394)  评论(0编辑  收藏  举报