我想设置 options[Symbol.iterator]
属性,以便在使用 for...of
语句迭代我创建的简单对象:
我希望能够通过设置 options[Symbol.iterator]
属性来让我创建的简单对象能够被 for...of
语句迭代:
options = {
male: 'John',
female: 'Gina',
rel: 'Love'
};
for(let p of options){
console.log(`Property ${p}`);
};
但是这段代码给我以下错误:
array.html:72 Uncaught TypeError: options[Symbol.iterator] is not a function
如何在上述简单对象上设置正确的迭代器函数?
已解决
// define the Iterator for the options object
options[Symbol.iterator] = function(){
// get the properties of the object
let properties = Object.keys(this);
let count = 0;
// set to true when the loop is done
isDone = false;
// define the next method, need for iterator
let next = () => {
// control on last property reach
if(count >= properties.length){
isDone = true;
}
return {done:isDone, value: this[properties[count++]]};
}
// return the next method used to iterate
return {next};
};
现在我可以在可迭代对象上使用for...of
语句:
for(let property of options){
console.log(`Properties -> ${property}`);
}
for...of
循环,集合必须具有[Symbol.iterator]
属性。对象字面量没有这样的属性,只有数组、集合、映射等才有。 - adeneoMap
。 - Bergi