JavaScript中数组循环的多种方式

JavaScript中数组循环的多种方式

技术背景

在JavaScript编程中,数组是一种常用的数据结构,对数组进行循环操作是常见的需求。不同的循环方式有各自的特点和适用场景,了解这些方式能让开发者根据具体需求选择最合适的方法。

实现步骤

1. 顺序 for 循环

1
2
3
4
5
6
var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
console.log(myStringArray[i]);
//Do something
}

此方法适用于所有环境,可使用 breakcontinue 进行流程控制,但代码较为冗长,且容易出现越界错误。

2. Array.prototype.forEach

1
2
3
4
const array = ["one", "two", "three"];
array.forEach(function (item, index) {
console.log(item, index);
});

使用ES6箭头函数会更简洁:

1
array.forEach(item => console.log(item));

该方法简洁、声明式,但不能使用 breakcontinue。在需要提前终止循环时,可先过滤数组元素。

3. ES6 for...of 语句

1
2
3
4
let colors = ['red', 'green', 'blue'];
for (const color of colors){
console.log(color);
}

for...of 可遍历多种可迭代对象,能使用正常的流程控制语句,适合串行异步值的迭代,但在针对旧浏览器时,转译后的输出可能不符合预期。

4. 避免使用 for...in

for...in 用于枚举对象属性,不适合用于数组,因为其迭代顺序不保证,且会枚举继承属性。

1
2
3
4
5
Array.prototype.foo = "foo!";
var array = ['a', 'b', 'c'];
for (var i in array) {
console.log(array[i]);
}

上述代码会输出 "a", "b", "c", "foo!"

其他循环方式

1. while 循环

1
2
3
4
5
6
let array = [1, 2, 3, 4, 5];
let length = array.length;
while(length > 0){
console.log(array[array.length - length]);
length--;
}

2. do...while 循环

1
2
3
4
5
6
let array = [1, 2, 3, 4, 5];
let length = array.length;
do {
console.log(array[array.length - length]);
length--;
} while (length > 0);

核心代码

顺序 for 循环

1
2
3
4
var arr = [1, 2, 3, 4, 5];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}

Array.prototype.forEach

1
2
const arr = [1, 2, 3, 4, 5];
arr.forEach(item => console.log(item));

ES6 for...of 语句

1
2
3
4
const arr = [1, 2, 3, 4, 5];
for (let element of arr) {
console.log(element);
}

最佳实践

性能优化

传统的 for 循环在性能上表现最佳,尤其是缓存数组长度时。

1
2
3
4
let arr = [1, 2, 3, 4, 5];
for (let i = 0, size = arr.length; i < size; i++) {
// Do something
}

函数式编程

使用 mapfilterreduce 等方法可以实现更简洁、易读的代码。

1
2
3
const myArray = [{x: 100}, {x: 200}, {x: 300}];
const newArray = myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]

常见问题

for...in 用于数组的问题

for...in 不适合用于数组,因为它会枚举继承属性,且迭代顺序不保证。

forEach 不能使用 breakcontinue

如果需要提前终止循环,可使用 for 循环或 for...of 语句。

稀疏数组的处理

不同的循环方式对稀疏数组的处理不同,forfor...of 会遍历数组的全部长度,forEach 只会处理实际存在的元素。在处理稀疏数组时,需要根据具体需求选择合适的循环方式。


JavaScript中数组循环的多种方式
https://119291.xyz/posts/2025-05-09.javascript-array-looping-methods/
作者
ww
发布于
2025年5月9日
许可协议