The JavaScript exception "is not iterable" occurs when the value which is given as the right hand-side of
for…of
or as argument of a function such as
Promise.all
or
TypedArray.from
, is not an
iterable object
.
TypeError: 'x' is not iterable (Firefox, Chrome) TypeError: 'x' is not a function or its return value is not iterable (Chrome)
The value which is given as the right hand-side of
for…of
or as argument of a function such as
Promise.all
or
TypedArray.from
, is not an
iterable object
. An iterable can be a built-in iterable type such as
Array
,
String
or
Map
, a generator result, or an object implementing the
可迭代协议
.
In JavaScript,
Object
s are not iterable unless they implement the
可迭代协议
. Therefore, you cannot use
for…of
to iterate over the properties of an object.
var obj = { 'France': 'Paris', 'England': 'London' };
for (let p of obj) { // TypeError: obj is not iterable
// …
}
Instead you have to use
Object.keys
or
Object.entries
, to iterate over the properties or entries of an object.
var obj = { 'France': 'Paris', 'England': 'London' };
// Iterate over the property names:
for (let country of Object.keys(obj)) {
var capital = obj[country];
console.log(country, capital);
}
for (const [country, capital] of Object.entries(obj))
console.log(country, capital);
Another option for this use case might be to use a
Map
:
var map = new Map;
map.set('France', 'Paris');
map.set('England', 'London');
// Iterate over the property names:
for (let country of map.keys()) {
let capital = map[country];
console.log(country, capital);
}
for (let capital of map.values())
console.log(capital);
for (const [country, capital] of map.entries())
console.log(country, capital);
生成器 are functions you call to produce an iterable object.
function* generate(a, b) {
yield a;
yield b;
}
for (let x of generate) // TypeError: generate is not iterable
console.log(x);
When they are not called, the
Function
object corresponding to the generator is callable, but not iterable. Calling a generator produces an iterable object which will iterate over the values yielded during the execution of the generator.
function* generate(a, b) {
yield a;
yield b;
}
for (let x of generate(1,2))
console.log(x);
Custom iterables can be created by implementing the
Symbol.iterator
method. You must be certain that your iterator method returns an object which is an iterator, which is to say it must have a next method.
const myEmptyIterable = {
[Symbol.iterator]() {
return [] // [] is iterable, but it is not an iterator -- it has no next method.
}
}
Array.from(myEmptyIterable); // TypeError: myEmptyIterable is not iterable
Here is a correct implementation:
const myEmptyIterable = {
[Symbol.iterator]() {
return [][Symbol.iterator]()
}
}
Array.from(myEmptyIterable); // []