这对我来说很好:
const iterable = [1, 2, 3];
for (const value of iterable) {
console.log(value);
}但是,这不起作用:
const iterable = {1:10, 2:20, 3:30};
for (const value of iterable) {
console.log(value);
console.log(iterable[value]);
}而不是给我这个错误:
Uncaught TypeError: iterable[Symbol.iterator] is not a function(…)我该怎么做呢?
这就是我现在要做的:
for(const value in iterable){
if (iterable.hasOwnProperty(value)) {
console.log(value);
console.log(iterable[value]);
}
}发布于 2016-12-16 18:12:53
for..of仅适用于iterable objects。你可以像这样实现一个迭代器:
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要迭代普通对象,而不是我认为很好的for...in,您可以使用Object.keys
const iterable = {1:10, 2:20, 3:30};
Object.keys( iterable ).forEach( key => {
console.log( iterable[key] );
}); // 10, 20, 30顺便说一下,你的第一个例子抛出了一个语法错误,也许你的意思是const iterable = [1,2,3]?那么它将会工作,因为数组是可迭代的对象。
https://stackoverflow.com/questions/41181393
复制相似问题