[英]Making plain objects iterable.(javascript)
So I'm working on a personal project after covering the first seven chapters of eloquent javascript by Marjin Heverbeke.因此,在完成 Marjin Heverbeke 的 eloquent javascript 的前七章之后,我正在着手一个个人项目。 Im creating school data handling system.
我正在创建学校数据处理系统。 So i already made my data structure which includes a lot of objects, so I created a test object to so that i could practice the iteration protocol, this is what i wrote
所以我已经制作了包含很多对象的数据结构,所以我创建了一个测试对象,以便我可以练习迭代协议,这就是我写的
let object = {a:'a',b:'b',c:'c',d:'d',e:'e'};
object[Symbol.iterator]=function(){
let keys = Object.keys(this);
let count=0;
return {
next(){
if(count>keys.length){
return {value: null, done:true};
}
else{
let value=this[keys[count]];
count++;
return {value, done:false};
}
}
}
}
but when i do this但是当我这样做时
for(let each of object){
console.log([each]);
}
it outputs它输出
//Array[undefined]
//Array[undefined]
//Array[undefined]
//Array[undefined]
//Array[undefined]
//Array[undefined]
//Array[undefined]
I don't know what is wrong oo, pls help.我不知道有什么问题哦,请帮忙。
Try this:尝试这个:
let object = {
a: 'a',
b: 'b',
c: 'c',
d: 'd',
e: 'e',
};
object[Symbol.iterator] = function () {
let keys = Object.keys(this);
let count = 0;
return {
next() {
if (count === keys.length) {
return {
value: null,
done: true,
};
}
let value = keys[count];
count++;
return {
value,
done: false,
};
},
};
};
for (let each of object) {
console.log([each]);
}
Note the errors were: let value=this[keys[count]];
注意错误是:
let value=this[keys[count]];
and if (count > keys.length)
和
if (count > keys.length)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.