let lila = { name: 'Lila', height: '5\'10"', weight: 185 };
lila[Symbol.iterator] = function* () {
var k;
for (k in this) {
yield [k, this[k]];
}
};
var iterator = lila[Symbol.iterator]();
console.log(iterator.next()); // get the first of a sequence of values
console.log([...lila]); // get all key/values pairs
const Lila = {
name: 'Lila',
height: `5'10"`,
weight: 185,
[Symbol.iterator]() {
let index = 0; // use index to track properties
let properties = Object.keys(this); // get the properties of the object
let Done = false; // set to true when the loop is done
return { // return the next method, need for iterator
next: () => {
Done = (index >= properties.length);
// define the object you will return done state, value eg Lila ,key eg
//name
let obj = {
done: Done,
value: this[properties[index]],
key: properties[index]
};
index++; // increment index
return obj;
}
};
}
};
6条答案
按热度按时间7vhp5slm1#
您可以使用迭代器将
Symbol.iterator
属性赋给对象。阅读更多关于在iteration protocols中使用
iterator.next
的信息。djmepvbi2#
这就是答案
sczxawaw3#
为什么你需要一个迭代器或生成器?保持简单,只需迭代对象...
eivnm1vs4#
你可以convert an object to an iterable (Array) with Object.entries
erhoui1w5#
你可以使用Object.keys()迭代一个对象的键,然后用一个迭代器函数封装它:
你可以这样使用它:
htzpubme6#
尝试 * 以下 *: