持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第12天,点击查看活动详情
语法
array.find(function(item, index, arr), ins)
参数
参数1:回调函数(必需)
参数2:传递给回调函数的this指针(可选)
注:当回调函数是箭头函数时,参数2无效,始终指向全局window变量
回调函数
参数1:当前元素
参数2:当前元素的下标
参数3:原数组
let list = [1, 2, 3];
list.find((item, index, arr) => {
console.log(item, index, arr);
});
this指针
let list = [1, 2, 3];
let ins = { haha: '我的传进来的this' };
list.find(function () {
console.log(this);
}, ins);
如果不传,默认是全局window变量:
let list = [1, 2, 3];
list.find(function () {
console.log(this);
});
返回值
返回符合测试条件的第一个数组元素值,如果没有符合条件的则返回 undefined。
let list = [1, 2, 2, 3];
let res = list.find(item => item === 2);
console.log(res);
为了更好地了解到底是不是返回第一个符合数组的元素,我们修改下测试用例:
let list = [
{name: 'Jane', score: 90},
{name: 'Lili', score: 90},
];
let res = list.find(item => item.score === 90);
console.log(res);
我们将score改成80,则在数组中找不到符合条件的元素,返回undefined
手写
理清需求
- 函数接收
2个参数,一个回调函数,一个this指向 - 函数会遍历数组每一项,找出第一个符合条件的项并返回,如果没有符合的,则返回
undefined - 回调函数接收
3个参数:当前元素、下标、原数组 - 回调函数可通过函数的第二个参数改变
this指向 根据需求,不难写出以下代码:
Array.prototype._find = function (callback, ins) {
let res;
for (let i = 0; i < this.length; i++) {
if (callback.call(ins, this[i], i, this)) {
res = this[i];
break;
}
}
return res;
};
测试
我们调用原生的find方法试试结果:
一模一样的,是不是so easy!
假如没有符合条件的,在我们手写的方法中是进不去for 循环的,那么res的值未定义就是undefined被直接返回了:
结语
今天关于数组find的介绍就讲到这里,关注我获取更多有关数组方法的讲解,后续会持续更新。我是末世未然,一个爱折腾的新晋奶爸,祝好