2022 答案
如果您问的是“foo 是否可迭代”,那么您可能来自一种语言(PHP、Python),其中该问题只有一个答案。 在现代 Javascript 中,存在不同类型的可迭代对象。因此,您必须根据要对变量执行的操作来检查迭代能力。
TL;DR
- 测试使用
forEach() 和 !!foo.forEach 进行迭代的能力,在数组上返回 true。
- 测试使用
for..of 和 !!foo[Symbol.iterator] 进行迭代的能力,在数组或字符串上返回 true。
- 测试使用
for..in 和 !!Object.keys(Object(foo)).length 进行迭代的能力,在数组、字符串或对象上返回 true。
长答案
让我们定义一些变量:
const someNumber = 42;
42
const someArray = [1,2,3];
(3) [1, 2, 3]
const someString = "Hello";
"Hello, world!"
const someObject = {a:"A", b:"B"};
{a: "A", b: "B"}
使用forEach() 测试可迭代性
哪些类型可以用forEach()迭代,用!!foo.forEach测试:
someNumber.forEach(x=>console.log(x));
VM1526:1 Uncaught TypeError: someNumber.forEach is not a function at <anonymous>:1:12
someArray.forEach(x=>console.log(x));
VM916:1 1
VM916:1 2
VM916:1 3
undefined
someString.forEach(x=>console.log(x));
VM957:1 Uncaught TypeError: someString.forEach is not a function at <anonymous>:1:12
someObject.forEach(x=>console.log(x));
VM994:1 Uncaught TypeError: someObject.forEach is not a function at <anonymous>:1:12
似乎只有 Array 可以使用 forEach() 进行迭代。
使用for..of 测试可迭代性
哪些类型可以用for..of迭代,用!!foo[Symbol.iterator]测试:
for (x of someNumber) { console.log(x); }
VM21027:1 Uncaught TypeError: someNumber is not iterable at <anonymous>:1:11
for (x of someArray) { console.log(x); }
VM21047:1 1
VM21047:1 2
VM21047:1 3
undefined
for (x of someString) { console.log(x); }
VM21065:1 H
VM21065:1 e
VM21065:1 l
VM21065:1 l
VM21065:1 o
undefined
for (x of someObject) { console.log(x); }
VM21085:1 Uncaught TypeError: someObject is not iterable at <anonymous>:1:11
Array 和 String 似乎可以用 for..of 进行迭代,但 Object 不是。并且 Number 和 Object 都抛出了错误。
使用for..in 测试可迭代性
哪些类型可以用for..in迭代,用!!Object.keys(Object(foo)).length测试:
for (x in someNumber) { console.log(x); }
undefined
for (x in someArray) { console.log(x); }
VM20918:1 0
VM20918:1 1
VM20918:1 2
undefined
for (x in someString) { console.log(x); }
VM20945:1 0
VM20945:1 1
VM20945:1 2
VM20945:1 3
VM20945:1 4
undefined
for (x in someObject) { console.log(x); }
VM20972:1 a
VM20972:1 b
undefined
Array、String 和 Object 似乎都可以使用for..in 进行迭代。虽然它没有迭代,但 Number 没有抛出错误。
在现代 ES6 Javascript 中,我看到 forEach 的使用频率远高于 for..in 或 for..of。但是 Javascript 开发人员必须意识到这三种方法之间的差异,以及每种方法的不同行为。