Javascript forEach() 遍历数组

javascript forEach()

javascript中 forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。

注意: forEach() 对于空数组是不会执行回调函数的。

语法

array.forEach(callbackFn(currentValue, index, arr), thisValue)

参数:

  • callbackFn(currentValue, index, arr) :必需。 数组中每个元素需要调用的函数。
  • currentValue : 必需。当前元素
  • index : 可选。当前元素的索引值。
  • arr : 可选。当前元素所属的数组对象。
  • thisValue : 可选。传递给函数的值一般用 "this" 值。如果这个参数为空, "undefined" 会传递给 "this" 值

其他形式语法:

// 箭头函数
forEach((element) => { /* … */ })
forEach((element, index) => { /* … */ })
forEach((element, index, array) => { /* … */ })

// 回调函数
forEach(callbackFn)
forEach(callbackFn, thisArg)

// 内联回调函数
forEach(function(element) { /* … */ })
forEach(function(element, index) { /* … */ })
forEach(function(element, index, array){ /* … */ })
forEach(function(element, index, array) { /* … */ }, thisArg)

实例:

计算数组所有元素相加的总和:

<button onclick="numbers.forEach(myFunction)">点我</button>
 
<p>数组元素总和:<span id="demo"></span></p>
 
<script>
var sum = 0;
var numbers = [65, 44, 12, 4];
 
function myFunction(item) {
    sum += item;
    demo.innerHTML = sum;
}
</script>

将数组中的所有值乘以特定数字:

<p>乘以: <input type="number" id="multiplyWith" value="10"></p>
<button onclick="numbers.forEach(myFunction)">点我</button>
 
<p>计算后的值: <span id="demo"></span></p>
 
<script>
var numbers = [65, 44, 12, 4];
 
function myFunction(item,index,arr) {
    arr[index] = item * document.getElementById("multiplyWith").value;
    demo.innerHTML = numbers;
}
</script>

forEach() 的 continue 与 break

forEach() 本身是不支持的 continue 与 break 语句的,我们可以通过 some 和 every 来实现。

使用 return 语句实现 continue 关键字的效果:

coninue实现

var arr = [1, 2, 3, 4, 5];

arr.forEach(function (item) {
    if (item === 3) {
        return;
    }
    console.log(item);
});

输出:
1
2
4
5
var arr = [1, 2, 3, 4, 5];

arr.some(function (item) {
        if (item === 2) {
                return;  // 不能为 return false
        }
        console.log(item);
});

输出:
1
3
4
5
false

break实现

var arr = [1, 2, 3, 4, 5];

arr.every(function (item) {
        console.log(item);
        return item !== 3;
});

输出:
1
2
3
false