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
JavaScript 之 手写every
最新推荐文章于 2024-06-14 11:01:38 发布