学好JavaScript基础:细说forEach

前言

使用过forEach的人大致有两种:普通使用,简简单单;复杂使用,总想搞出点花样来,结果一些莫名其妙的bug就出现了,解决这些bug所花费的时间都可以换一种思路实现了,能用作for循环的,又不只是forEach。没错,笔者就是后者,终究是自己“学艺不精”。于是乎,花点时间,结合自己的实际开发经验,再来好好理理forEach。

语法

forEach()是数组对象的一个原型方法,该方法会对数组中的每一个元素执行一次给定的回调函数,并且始终返回undefined。类数组对象是没有forEach方法的,例如arguments。forEach的用法比较简单:

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

实际例子:

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

参数说明:

callback:数组中每一个元素将要执行的回调函数,可以有1-3个参数

  • currentValue:当前正在处理的元素,必传
  • index:当前正在处理的元素的索引,可选参数
  • array:forEach方法操作的原数组对象,可选参数

thisArg:当前执行callback回调函数时,回调函数的this指向,默认指向的全局对象,可选参数

语法看起来并不复杂,那么看看是否会犯下面的错误用法。

错误用法

forEach()在第一次调用callback时就会确定遍历的范围,一般来说会按照索引升序为数组中的有效元素执行一次callback函数。如果是未初始化的数组项或者在调用forEach()后添加到数组中的项都不会被访问到,如果在遍历时删除数组中的元素,则可能会出现意外的情况。

调用后添加元素,将不会被访问到

const arr = [1,,,2,4];
console.log(arr.length); // 5
let callbackCounts = 0;
arr.forEach(item => {
    console.log(item); // 1 2 4
    callbackCounts++;
    arr.push(6); // 调用后添加元素,将不会被访问到
})
console.log(callbackCounts); // 3
console.log(arr); // [1,,,2,4,6,6,6]

删除数组中的元素

const arr = ['a', 'b', 'c', 'd'];
console.log(arr.length); // 4
let callbackCounts = 0;
arr.forEach((item, index) => {
    // arr.shift();
    console.log(item); // 'a','b','d',其中'c'会被跳过
    if (item === 'b') {
        // arr.shift(); // 删除头部,arr的结果:['b', 'c', 'd']
        arr.splice(index, 1); // 删除当前元素,arr的结果:['a', 'c', 'd']
        // arr.splice(-1); // 删除最后一个元素,arr的结果:['a', 'b', 'c']
    }
    callbackCounts++;
})
console.log(callbackCounts); // 3
console.log(arr); // ['b', 'c', 'd']

删除元素时情况可能会比较复杂一点,感兴趣的朋友可以自己测试,我们可以这么理解:

  • forEach在调用时就确定了遍历范围,传递给callback的值是forEach在遍历到该元素时的值,即使在callback中删除了数组中该元素,但是值已经传递进来
  • 如果是有效的值,callbackCounts会递增。在下一轮循环时,forEach会根据上一轮循环时的索引得到当前循环对应的值,注意此时数组长度已经改变,就会出现“跳过”的现象
  • 然后重复操作,知道数组遍历完毕

搞懂了”跳过“,你还敢想当然的删除数组中的数据吗?

修改原数组中的数据

既然不能添加和删除,那我要是修改呢?其实修改数组中的元素,不是不可以,只是要注意使用方法。

1.如果数组中是基本数据类型:string、number、boolean等,只使用回调函数的第一个参数修改数组中的值是不会影响原数组的

const arr = [1,2,3,4,5]
arr.forEach((item, index, array) => {
    item+=1; // [1,2,3,4,5]
    // arr[index]+=1; // [2,3,4,5,6]
    // array[index]+=1; // [2,3,4,5,6]
})
console.log(arr);

2.如果数组中的是引用数据类型:object等,直接替换数组项是不会影响原数组的

const arr = [
    {name: '张三', id: 1},
    {name: '李四', id: 2}
]
arr.forEach((item, index, array) => {
    if (item.id === 2) {
        item = {name: '王五', id: item.id}; // 张三、李四
        // Object.assign(item, {name: '王五', id: item.id}); // 张三、王五
        // arr[index] = {name: '王五', id: item.id}; // 张三、王五
        // array[index] = {name: '王五', id: item.id}; // 张三、王五
    }
})
console.log(arr);

数组对象在遍历时,实际上是将数组项的引用地址赋值给item,如果将另一个对象的引用地址重新赋值给item,并不会改变原引用地址的数据,也就不会影响原数组。

3.如果数组中的是引用数据类型:object等,此时我们只修改数组项的某一个属性,这个时候是会影响原数组的

const arr = [
    {name: '张三', id: 1},
    {name: '李四', id: 2}
]
arr.forEach((item, index, array) => {
if (item.id === 2) {
    item.name = '王五';
    // arr[index].name = '王五'; // 张三、王五
    // array[index].name = '王五'; // 张三、王五
}
})
console.log(arr); // 张三、王五

道理呢也和2类似,item指向的是引用地址,修改属性相当于是修改了引用地址中对象的属性,也就会修改原数组

综上我们可以发现,如果要在forEach中修改原数组,那么需要在其回调函数中,通过索引index或者借助Object.assgin()才可以实现,最终原理都是修改引用地址中的数据,而不是直接修改。

回调函数中使用异步函数

异步函数和同步函数的执行顺序此处就不细说,简单来说就是同步代码先于异步代码执行。

看一个例子:

const arr = [1,2,3,4,5]
let sum = 0;
let callbackCounts = 0;
function Sum(a, b) {
    return new Promise((resovle) => {
        resovle(a + b)
    })
}
arr.forEach(async (item, index, array) => {
    sum = await Sum(sum, item)
})
console.log(sum); // 0

实际得到的求和的值并不是我们期待的15,而是0。

如果我们需要实现异步求和,可以使用for循环实现:

const arr = [1,2,3,4,5]
let sum = 0;
let callbackCounts = 0;
function Sum(a, b) {
    return new Promise((resovle) => {
        resovle(a + b)
    })
}
(async function() {
    for (let item of arr) {
        sum = await Sum(sum, item)
    }
    console.log(sum); // 15
})();

使用return结束循环

在使用for循环时,我们一般可使用breakreturn来跳出循环,抛出异常也可以,但是这不是正常的开发流程。我们来试一下在forEach中使用break、return有没有作用:

forEach结束循环

const arr = [1,2,3,4,5]
let callbackCounts = 0;
arr.forEach((item, index, array) => {
    callbackCounts++;
        if (item === 2) {
        return; // forEach中不能使用break,即使使用return,也无法中止循环
    }
})
console.log(arr.length, callbackCounts); // 5 5

如果非得要跳出forEach循环,首先建议的是使用其他循环方法,例如:for、for of、for in、map等,其次我们可以考虑抛出一个异常来跳出forEach循环:

const arr = [1,2,3,4,5]
let callbackCounts = 0;
try {
    arr.forEach((item, index, array) => {
        callbackCounts++;
        if (item === 2) {
            throw 'throw forEach';
        }
    })
} catch (e) {
    console.log(arr.length, callbackCounts); // 5 2
}

如果真要使用throw来抛出异常,那么使用其他循环方法不香吗

未传入this

forEach()也可能存在this指向问题,例如:

function Counter() {
    this.sum = 0;
}
Counter.prototype.add = function (array) {
    array.forEach(function(element) {
        this.sum += element;
    });
}
const obj = new Counter();
obj.add([1,2,3,4,5])
console.log(obj.sum); // 0

未指定this,则默认未window对象,此时的this.sum为undefined,而我们想的是this指向传入的数组。那么需要传入this或者使用箭头函数。

array.forEach((element) => {
    this.sum += element;
});
array.forEach(function(element) {
    this.sum += element;
}, this);

正确用法

避免错误用法,当然就是正确用法咯。

其实forEach在设计出来只是为了简化for循环的遍历,如果要过多的进行其他操作,就违背了设计初衷了。每一个API都有自己的适用范围,如果坚持要一把梭,可能就会踩很多坑。

简单总结一下正确的使用方法:

  • 最好只限于遍历原数组,不涉及修改原数组中的数据
  • 避免在回调函数中存在异步操作
  • 不能使用return
  • forEach()的回调函数使用箭头函数,可避免this指向问题

总结

  • forEach本身并不会改变原数组,但是其回调函数可能会修改。如果真要修改原数组,建议使用mapfilter等方法
  • forEach方法始终返回undefined,这使得forEach无法像mapfilter一样可以链式调用
  • 除了抛出异常外,forEach无法被中止或者跳出循环,如果要跳出循环,建议使用其他for循环方法
  • 如果是涉及异步函数,可以考虑使用for await of代替forEach

版权声明:
作者:Lei钟意
链接:https://leixf.cn/archives/818
来源:跃动指尖
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>
文章目录
关闭
目 录