Javascript对象如何通过for语句进行迭代? [英] How can a Javascript object become iterable with for...of statement?
问题描述
我想设置选项[Symbol.iterator]
属性,以便迭代我用创建的简单对象。 .of
声明:
I would like to set the options[Symbol.iterator]
property in order to iterate on the simple objects I create with the for...of
statement :
options = {
male: 'John',
female: 'Gina',
rel: 'Love'
};
for(let p of options){
console.log(`Property ${p}`);
};
但此代码给出了以下错误:
But this code gives me the following error:
array.html:72 Uncaught TypeError: options[Symbol.iterator] is not a function
如何在上面的简单对象上设置正确的迭代器函数?
How I can set the right iterator function on a simple object as above?
Solved
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};
};
我可以将用于......
我的对象上的语句现在是可迭代的:
And I can use the for...of
statement on my object now iterable :
for(let property of options){
console.log(`Properties -> ${property}`);
}
推荐答案
使用 for ... of
循环你应该使用 [Symbol.iterator]
key为你的对象定义一个合适的迭代器。
To use for...of
loop you should define an appropriate iterator for your object using [Symbol.iterator]
key.
这是一个可能的实现:
let options = {
male: 'John',
female: 'Gina',
rel: 'Love',
[Symbol.iterator]: function * () {
for (let key in this) {
yield [key, this[key]] // yield [key, value] pair
}
}
}
尽管在大多数情况下,最好使用普通的迭代对象...在
循环中。
Though, in most cases it'll be better to iterate over objects using plain for...in
loop instead.
或者你可以使用 Object.keys $ c $将对象转换为可迭代数组c>,
Object.values
或 Object.entries
(ES7)。
Alternatively you could convert your object to iterable array using Object.keys
, Object.values
or Object.entries
(ES7).
这篇关于Javascript对象如何通过for语句进行迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!