原生JavaScript实现filter和reduce函数

原生JavaScript实现filter和reduce函数

今天又是手写JavaScript中API的一天

原生JavaScript实现filter函数

filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。

`Array.prototype.myfilter = function(callback, thisArg = this) {
if (typeof callback != 'function') {
    throw new TypeError(callback + "is not a function");
}
if (this == undefined) {
    throw new TypeError("this is null or not undefined");
}	//判断验证参数类型
let res = [];
const o = Object(this)
    // const o = Array.from(this);
const len = o.length;
for (let i = 0; i < len; i++) {
    if (i in o) { 
        if (callback.call(thisArg, o[i], i, o)) {
			//用每个回调函数判断用数组中的每个元素作为参数是否能返回真值
            res.push(o[i]);
        }
    }
}
return res;
}`

原生JavaScript实现reduce

reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。

`rray.prototype.myReduce = function(callback, initialValue) {
if (typeof callback != 'function') { //首先检测回调函数的类型,如果不是函数抛出异常
    throw new TypeError(callback + "is not a function");
}
if (this == undefined) { //如果this没有指向任何对象,抛出异常
    throw new TypeError("this is null or not undefined");
}
const o = Object(this) //保证this是一个对象,拥有可遍历的属性
    // const o = Array.from(this);
const len = o.length;
let temp = initialValue;
let k = 0;
if (temp != undefined) {
    while (k < len && !(k in o)) {
        //检测k位上是否有值
        k++;
    }
    if (k >= len) {
        throw new TypeError('reduce of empty array with no initial value')
    }
    temp = o[k++]
}

for (let i = k++; i < len; i++) {
    if (i in o) {
        temp = callback.call(undefined, temp, o[i], i, o)
	//将每个数组对象的执行结果作为下一次的起始值
    }
}

return temp;
}`
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值