gpt4 book ai didi

javascript - Javascript 对象如何通过 for...of 语句变得可迭代?

转载 作者:可可西里 更新时间:2023-11-01 01:56:05 28 4
gpt4 key购买 nike

<分区>

我想设置 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

如何在上面的简单对象上设置正确的迭代器函数?

Solved

 // 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}`);
}

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com