JavaScript 之 手写every

const array = [1, 2, 3, 4, 5, 6, 7, 8];
// 第一个参数是 函数
// 第二个参数是 this 的指向 (可选)
Array.prototype._every = function(callback, thisArg = window){
    // 第一个参数不是一个函数的话, 抛出异常
    if (typeof callback !== 'function') {
        throw new TypeError(callback + ' is not a function');
    }
    let flag = true;
    const len = this.length;
    for (let i = 0; i < len; i++) {
        // 将处理后的数据 push 到新的数组中
        if(!callback.apply(thisArg, [this[i], i, this])){
            flag = false;
            break;
        }
    }
    return flag;
}

/**
 * @param item 当前正在处理的数组元素的值。
 * @param index 当前正在处理的数组元素的索引。(可选)
 * @param arr 正在遍历的数组本身。(可选):
 * @returns {Object} 返回函数处理后的值
 */
function handleArr(item, index, arr) {
    console.log(this); // 这里的 this 指向的是 obj
    return item % 2 === 0; // 所有数据 乘 2
}

const obj = {name: '张三'};

const allEven = array._every(handleArr, obj);
console.log(allEven , 'allEven///'); //  输出 false,因为有奇数存在

const _array = [2, 4, 6, 8];
const _allEven = _array ._every(handleArr, obj);
console.log(_allEven , '_allEven///'); //  输出 true
  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值