常用数组方法
JavaScript中为我们提供了很多原生的数组API。为我们平时开发提供了很大的帮助。今天我们就来实现几个常用的数组API。知其然不知所以然是不行的。我们要知其然知其所以然。
forEach方法
array.forEach(callback[, thisObject]);
**forEach**接受两个参数:
第一个参数:回调函数
第二个参数:执行回调时用作此对象的对象
下面我们就实现它
let arr = [1,2,3]
Array.prototype.myForEach = function (fn,thisValue){
// 用原生的for遍历,这里面的this是谁调用这个函数,this就是谁
for (let i = 0;i < this.length;i++){
// 回调函数有三个参数,当前值,当前下标,和当前数组
fn.call(this,this[i],i,this)
}
}
arr.myForEach(function (value,index){
console.log(value,index);
})
显示结果:
map方法
map方法要注意的就是它会把每个元素的结果放到一个新数组返回给我们
array.map(callback[, thisObject]);
map接受两个参数:
第一个参数:回调函数
第二个参数:执行回调时用作此对象的对象
实现代码:
let arr = [3,1,3,7,0,0,6,0,7]
Array.prototype.myMap = function (fn) {
// 创建一个新数组
let result = [];
// 利用循环拿到当前数组的每一个元素
this.forEach((value,i) => {
// 因为map接收的是数组中的每一个元素,所以把元素,下标,当前数组传进去
result.push(fn.call(this, value, i, this))
})
// 返回新的数组
return result
}
let a = arr.myMap(function (item) {
return item > 3
})
console.log(a);
执行结果:
filter方法
filter方法会把满足条件的放到一个新数组中返回给我们
filter接受两个参数:
第一个参数:回调函数
第二个参数:执行回调时用作此对象的对象
实现代码:
let arr = [3,1,3,7,0,0,6,0,7]
Array.prototype.myFilter = function (fn) {
//因为filter是返回一个满足条件的新的数组
let result = []
// 遍历要过滤的数组
this.forEach((value,i) =>{
// 因为filter是将满足条件的数组存放到新的数组,所以要加个判断
if (fn.call(this,value,i,this)){
result.push(value)
}
})
return result
}
let a = arr.myFilter(function (value) {
return value > 1
})
console.log(a);
执行结果:
reduce方法
接收一个函数作为累加器,遍历数组中的每个值(从左到右),最终计算并返回为一个值
reduce接受两个参数:
第一个参数:回调函数
第二个参数:用作第一次调用回调的第一个参数的对象。
实现代码:
let arr = [1,2,3]
Array.prototype.myReduce = function (fn, initialValue) {
if (this.length === 0) return;
// 判断是否有第二个参数,因为第二个参数可以用作第一次调用回调的第一个参数的对象。
// 有第二个参数就赋值给result
let result = initialValue || arr[0];
// 因为上面做了一个判断,如果没有第二个参数就会使用数组第一个元素
// 这里进一步判断从数组那个位置开始
let startIndex = initialValue ? 0 : 1;
const length = this.length;
for (let i = startIndex; i < length; i++) {
result = fn.call(this, result, this[i], i, this);
}
return result;
}
let a = arr.myReduce(function (a,b) {
return a + b
},1)
console.log(a);
执行结果:
这里因为指定第二个参数为1,所以执行结果为7