Javascript中forEach和for循环的区别
本文详细描述了forEach和for 循环之间的区别。下面给出两者之间的基本区别。
For 循环: JavaScript for 循环用于对数组或元素进行指定次数的迭代。如果知道一定数量的迭代,就应该使用它。
句法:
for (initialization; condition; increment)
{
// code to be executed
}
例子:
Javascript
Javascript
numbers = [1, 2, 3, 4, 5];
numbers.forEach((number, index) => {
console.log('Index: ' + index +
', Value: ' + number);
});
输出:
1
2
3
4
5
forEach 循环: forEach() 方法也用于遍历数组,但它使用的函数与经典的“for 循环”不同。它为数组的每个元素以及以下参数传递一个回调函数:
- Current Value(必填):当前数组元素的值
- 索引(可选):当前元素的索引号
- Array(可选):当前元素所属的数组对象
我们需要一个回调函数来使用 forEach 方法遍历一个数组。
句法:
numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
// code to be executed
});
对于数组的每一个元素,函数都会被执行。回调应该至少有一个参数代表数组的元素。
示例 1:此示例显示了带有回调函数的 forEach 方法。
这
输出:
1
2
3
4
5
示例 2:此示例显示了在 forEach 方法中使用 index 参数。
Javascript
numbers = [1, 2, 3, 4, 5];
numbers.forEach((number, index) => {
console.log('Index: ' + index +
', Value: ' + number);
});
输出:
Index: 0, Value 1
Index: 1, Value 2
Index: 2, Value 3
Index: 3, Value 4
Index: 4, Value 5
For Loop | forEach Loop |
It is one of the original ways of iterating over an array. | It is a newer way with lesser code to iterate over an array. |
It is faster in performance. | It is slower than the traditional loop in performance. |
The break statement can be used to come out from the loop. | The break statement cannot be used because of the callback function. |
The parameters are the iterator, counter, and incrementor. | The parameters are the iterator, index of item, and array to iterate. |
It works with the await keyword. | The await keyword cannot be used due to the callback function. It may lead to incorrect output. |