Как объект Javascript может стать итеративным с for ... of Statement? [Дубликат]
На этот вопрос уже есть ответ здесь:
Использование объектов в цикле For 14 ответовЯ хотел бы установить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}`);
}