JavaScript数组循环方法全解析

JavaScript数组循环方法全解析

技术背景

在JavaScript开发中,经常需要对数组进行遍历操作。随着JavaScript的发展,提供了多种循环数组的方式,每种方式都有其特点和适用场景。了解这些方法有助于开发者根据具体需求选择最合适的循环方式,提高代码的效率和可读性。

实现步骤

1. 使用for-of(隐式使用迭代器,ES2015+)

1
2
3
4
const a = ["a", "b", "c"];
for (const element of a) {
console.log(element);
}

for-of循环会隐式地从数组获取迭代器,并按顺序遍历数组元素。它的优点是代码简洁,支持异步操作。

2. 使用forEach及其相关方法(ES5+)

1
2
3
4
const a = ["a", "b", "c"];
a.forEach((element) => {
console.log(element);
});

forEach接受一个回调函数,对数组的每个元素执行该回调。ES5还定义了其他相关方法,如everysomefiltermapreducereduceRight等。

3. 使用简单的for循环

1
2
3
4
5
const a = ["a", "b", "c"];
for (let index = 0; index < a.length; ++index) {
const element = a[index];
console.log(element);
}

简单的for循环是最传统的方式,灵活性高,可以控制循环的起始、结束和步长。

4. 正确使用for-in

1
2
3
4
5
6
7
8
9
10
const a = [];
a[0] = "a";
a[10] = "b";
a[10000] = "c";
for (const name in a) {
if (Object.hasOwn(a, name) && /^0$|^[1-9]\d*$/.test(name) && name <= 4294967294) {
const element = a[name];
console.log(element);
}
}

for-in主要用于遍历对象的可枚举属性,在数组上使用时需要添加一些检查来确保只处理数组元素。

5. 显式使用迭代器(ES2015+)

1
2
3
4
5
6
7
const a = ["a", "b", "c"];
const it = a.values();
let entry;
while (!(entry = it.next()).done) {
const element = entry.value;
console.log(element);
}

显式使用迭代器可以更精细地控制迭代过程。

对于类数组对象

  • 使用for-of:只要对象提供了迭代器,就可以使用for-of循环。
1
2
3
4
const divs = document.querySelectorAll("div");
for (const div of divs) {
div.textContent = Math.random();
}
  • 使用forEach及其相关方法:可以通过Function#callFunction#apply将数组方法应用于类数组对象。
1
2
3
Array.prototype.forEach.call(node.childNodes, (child) => {
// Do something with `child`
});
  • 创建真正的数组:可以使用Array.from、扩展语法(...)或Array.prototype.slice.call将类数组对象转换为真正的数组。
1
const divs = Array.from(document.querySelectorAll("div"));

核心代码

for-of循环异步示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function delay(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}

async function showSlowly(messages) {
for (const message of messages) {
await delay(400);
console.log(message);
}
}

showSlowly([
"So", "long", "and", "thanks", "for", "all", "the", "fish!"
]);

forEach循环异步问题示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function delay(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}

async function showSlowly(messages) {
messages.forEach(async message => {
await delay(400);
console.log(message);
});
}

showSlowly([
"So", "long", "and", "thanks", "for", "all", "the", "fish!"
]);

最佳实践

  • 优先使用for-of:当需要遍历可迭代对象且代码需要支持异步操作时,for-of是首选。
  • 使用forEach处理同步操作:如果只处理同步代码,且不需要提前终止循环,forEach是一个简洁的选择。
  • 使用简单for循环处理复杂逻辑:当需要更精细地控制循环过程,如改变循环索引或提前终止循环时,使用简单的for循环。

常见问题

1. for-in遍历数组的问题

for-in会遍历对象的所有可枚举属性,包括继承的属性,并且遍历顺序不保证,因此不适合直接用于遍历数组。

2. forEach不支持异步操作

如果在forEach的回调函数中使用异步操作,forEach不会等待异步操作完成就会继续执行下一次迭代。

3. 旧浏览器兼容性问题

一些较新的方法(如for-of、forEach等)在旧浏览器中可能不支持,需要进行polyfill处理。


JavaScript数组循环方法全解析
https://119291.xyz/posts/2025-04-17.javascript-array-loop-methods-analysis/
作者
ww
发布于
2025年4月17日
许可协议