【发布时间】:2016-06-19 14:06:39
【问题描述】:
我想设置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]属性。对象字面量没有这样的属性,只有数组、集合、映射等有 -
您想为此使用
Map。
标签: javascript debugging ecmascript-6 iterator for-of-loop