这对我来说很好:
const iterable = [1, 2, 3];
for (const value of iterable) {
console.log(value);
}
Run Code Online (Sandbox Code Playgroud)
但是这不起作用:
const iterable = {1:10, 2:20, 3:30};
for (const value of iterable) {
console.log(value);
console.log(iterable[value]);
}
Run Code Online (Sandbox Code Playgroud)
而是给我错误:
Uncaught TypeError: iterable[Symbol.iterator] is not a function(…)
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
这就是我现在所做的:
for(const value in iterable){
if (iterable.hasOwnProperty(value)) {
console.log(value);
console.log(iterable[value]);
}
}
Run Code Online (Sandbox Code Playgroud)
paw*_*wel 17
for..of仅适用于可迭代对象.你可以实现这样的迭代器:
const iterable = {
[Symbol.iterator]() {
return {
i: 1,
next() {
if (this.i <= 3) {
return { value: 10 * this.i++, done: false };
}
return { value: undefined, done: true };
}
};
}
};
for (const value of iterable2) {
console.log(value);
} // 10, 20, 30
Run Code Online (Sandbox Code Playgroud)
要迭代普通对象,除了for...in我认为没问题,你可以使用Object.keys:
const iterable = {1:10, 2:20, 3:30};
Object.keys( iterable ).forEach( key => {
console.log( iterable[key] );
}); // 10, 20, 30
Run Code Online (Sandbox Code Playgroud)
BTW你的第一个例子抛出语法错误,也许你的意思const iterable = [1,2,3]?然后它将工作,因为数组是可迭代的对象.