Javascript 通用 For 循环

Javascript Generic For Loop

有什么方法可以创建一个通用的 for 循环来正确地循环数组或对象吗?我知道我可以编写以下 for 循环,但它也会循环遍历将添加到数组的其他属性。

for (item in x) {
   console.log(item)
}

我指的是将迭代的 for 循环:

x = [1, 2]
x.foo = "foo"
y = {first:1, second: 2}

x 作为

1
2  

y 作为

first
second

这背后的原因是直到运行时我才知道 x 是什么(数组或对象)。创建一个将在运行时检查的函数是我唯一的选择吗?

使用 for..of loop.

遍历数组

const array = [1, 2];
array.foo = "test";
for (const number of array) {
    console.log(number); // skips array.foo
}

迭代对象

const object = {
    some: "string",
    number: 42
};
for (const [key, value] of Object.entries(object)) {
    console.log(key, value);
}

无论如何,从代码风格的角度来看,你仍然应该在迭代之前检查你的对象是否是一个数组。您可以使用 Array.isArray 来实现。因此,假设 data 是对象或数组:

if (Array.isArray(data)) {
    for (const element of data) {
        // Iterate over array
    }
}
else {
    for (const [key, value] of Object.entries(data)) {
        // Iterate over object
    }
}

通用循环

由于在 JavaScript、typeof [] === "object" 中(即数组是使用元素索引作为其键的对象),您可以将其简化为 单循环 Object.entries:

for (const [key, value] of Object.entries(data)) {
    // For arrays, `key` will be the index
}

请注意,后一种方法不会正确地排除动态属性(例如 array.foo),因为您将迭代 Object.entries 的结果。如果您 需要进行此排除,请使用两个带有 Array.isArrayfor..of 循环,如上所示。

如果根据您的预期输出只是您需要的 index/key 值,这里是一个简单的单行代码。

function loop(x) {
  return (Array.isArray(x) ? x : Object.keys(x)).forEach(el => console.log(el));
}

loop(x); // 1 2
loop(y); // First Second

DEMO