手写数组方法(二):forEach

587 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第10天,点击查看活动详情

语法

array.forEach(function(item, index, arr), ins)

参数

参数1:回调函数(必需

参数2:传递给回调函数的this指针(可选)

回调函数

参数1:当前元素

参数2:当前元素的下标

参数3:原数组

let list = [1, 2, 3];
list.forEach(function(item, index, arr) {
    console.log(item, index, arr);
});

2f720e2baf4c024731557c0ff0319e3.png

this指向

一般第二个参数我们很少会去使用,是没用吗?还是我们不知道怎么用

let list = [1, 2, 3];
let fruits = ['apple', 'orange', 'watermelon'];
list.forEach(function(item, index, arr) {
    const res = {};
    res[this[index]] = item;
    console.log(res);
}, fruits);

image.png

???就这,很鸡肋呀,我们完全可以这样,不传第二个参数,直接使用变量fruits代替this

let list = [1, 2, 3];
let fruits = ['apple', 'orange', 'watermelon'];
list.forEach(function(item, index, arr) {
    const res = {};
    res[fruits[index]] = item;
    console.log(res);
});

image.png

并且,我们更习惯用箭头函数来写,箭头函数在这里还读不到传进来的值:

269d8d6d382c33011d7ae98ba6dc2bc.png

综上:第二个参数了解就好,没啥用我感觉,有大佬知道这第二个参数的妙用欢迎指正。

使用

遍历数组

let fruits = ['apple', 'orange', 'watermelon'];
fruits.forEach((item) => {
    console.log(item)
});

image.png

返回值

let fruits = ['apple', 'orange', 'watermelon'];
const res = fruits.forEach((item) => item);
console.log(res);

image.png

forEach不同于map,函数并没有返回值

改变数组

使用forEach能否改变原数组?

直接赋值

let fruits = ['apple', 'orange', 'watermelon'];
fruits.forEach((item, index) => {
    fruits[index] = 'eat ' + item;
});
console.log(fruits);

image.png

通过回调函数参数

image.png

改变第三个参数其实就是改变了原数组!效果是一样的。

手写

理清需求

  • 函数接收2个参数,一个回调函数,一个this指向
  • 函数会遍历数组每一项
  • 回调函数接收3个参数:当前元素、下标、原数组
  • 回调函数可通过函数的第二个参数改变this指向
  • 函数无返回值 根据需求,不难写出以下代码:
Array.prototype._forEach = function(callback, ins) {
    for(let i = 0; i < this.length; i++) {
        callback.call(ins, this[i], i, this);
    }
};

测试

let list = [1, 2, 3];
let res = list._forEach(function(item, index, arr) {
    console.log(item, index, arr, this);
}, {haha: '我是this'});
console.log(res);

image.png

更严谨的写法

Array.prototype._forEach = function(callback, ins) {
    if(typeof callback !== 'function') throw Error('回调函数不是一个函数~');
    for(let i = 0; i < this.length; i++) {
        callback.call(ins, this[i], i, this);
    }
};
let list = [1, 2, 3];
list._forEach('a');

image.png

结语

今天关于数组forEach的介绍就讲到这里,关注我获取更多有关数组方法的讲解,后续会持续更新。我是末世未然,一个爱折腾的新晋奶爸,祝好