我們的志工尚未將本文翻譯為 正體中文 (繁體) 版本。加入我們,幫忙翻譯!
您也可以閱讀本文的 English (US) 版本。

Message

TypeError: 'x' is not iterable (Firefox, Chrome)
TypeError: 'x' is not a function or its return value is not iterable (Chrome)

Error type

TypeError

What went wrong?

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 iterable protocol.

Examples

Iterating over Object properties

In JavaScript, Objects are not iterable unless they implement the iterable protocol. 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);

Iterating over a generator

Generators 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);

See also

文件標籤與貢獻者

此頁面的貢獻者: amitsharma14393, fscholz, SphinxKnight, nbp
最近更新: amitsharma14393,