JS实现数组的常用方法
- 编程思路:先确定方法要传入的参数和返回的值,再通过原型定义,在Array的原型上添加自定的方法,验证是否达到预期效果。
1、find的功能
(function(currentValue, index, arr), thisValue)
- 功能:返回通过测试(函数内判断)的数组的第一个元素的值。简单理解就是:传入判断条件,判断数组各个元素,返回满足条件的第一个值。
- 当数组中的元素在测试条件时返回 true 时, find() 返回符合条件的元素,之后的值不会再调用执行函数。
- 如果没有符合条件的元素返回 undefined
- 注意: find() 对于空数组,函数是不会执行的。
- 注意: find() 并没有改变数组的原始值。
2、分析
- 分析:
- 传入:参数1为条件函数、参数2(可选)为调用的数组(默认是this)。
- 返回: 返回满足条件的第一个元素,不满足条件则返回undefined
3、实现与测试
- 实现:
Array.prototype.myFind = function (condition, arr = this) {
//将满足条件的元素放入到临时的数组中
let temp = [];
//遍历当前数组
for (let i = 0, len = arr.length; i < len; i++) {
const item = arr[i];
// 如果第一项存在,则停止遍历
if (temp[0]) {
break;
} else{
// 如果第一项不存在,则执行判断语句,满足则推进栈。不满足则继续遍历
if (condition(item, i, arr)) {
temp.push(item)
}
}
}
//可以直接只返回temp[0],全都不满足条件时,自然为undefined
return temp[0] || undefined
}
- 测试:
const myCondition = function(item, index, arr){ return item > 2}
[1,2,3,4].myFind(myCondition)//3
const myCondition = function(item, index, arr){ return item > 5}
[1,2,3,4].myFind(myCondition)//undefined