forEach函数

286 阅读1分钟

forEach函数

Array.prototype.forEach()

1. 语法

arr.forEach(callback(currentValue [, index [, array]])[, thisArg])

2. 参数详解

callback 为数组中每个元素执行的函数,该函数接收一至三个参数:

i. currentValue

数组中正在处理的当前元素。

ii. index 可选

数组中正在处理的当前元素的索引。

iii. array 可选

forEach() 方法正在操作的数组。

iiii. thisArg 可选

可选参数。当执行回调函数 callback 时,用作 this 的值。

3. 返回值

undefined。

4. 可依次向 callback 函数传入三个参数:

i. 数组当前项的值

ii. 数组当前项的索引

iii. 数组对象本身

如果 thisArg 参数有值,则每次 callback 函数被调用时,this 都会指向 thisArg 参数。如果省略了 thisArg 参数,或者其值为 nullundefinedthis 则指向全局对象。

5. forEach 不会直接改变调用它的对象,但是那个对象可能会被 callback 函数改变。

6. 关于中止或跳出循环

除了抛出异常以外,没有办法中止或跳出 forEach() 循环。 (即:不支持break, 使用return无效等)

如果需要中止或跳出循环,不应使用forEach()

若需要提前终止循环,可以使用一个简单的 for 循环

for...of / for...in 循环
Array.prototype.every()
Array.prototype.some()
Array.prototype.find()
Array.prototype.findIndex()

7. 示例:

归并排序中最后使用forEach起到修改原数组的效果。

Array.prototype.merge = function(){
    const rec = (arr) => {
        ...
        return res;
    }
    const res = rec(this);
    res.forEach((n,i) => {this[i] = n;
}
const arr = [...];
arr.merge();