我们来写一个 each 方法,然后挂载到 Array 的 prototype 上
要实现的功能:
- 必传参数 callback,如果有异常则抛出异常
- 如果只有一个callback,则里面的 this 指向 window
- 如果有第二个参数 obj, 则把 this 执行第二个参数 obj
- 生成一个新的数组,用来返回处理过后的数据
function each (callback, obj) {
let newArr = [];
// 如果有异常,抛出
try{
if (callback === undefined) throw new Error("There should be a callback function in each method");
if (callback !== undefined && typeof callback !== "function") throw new Error("Callback is not a function");
}
catch (err) {
console.error(err);
return false
}
// return value
let flag;
// judge function
function judge (bol, arrValue) {
if (!bol) newArr.push(arrValue);
else {
newArr.push(bol);
}
}
// 循环数组
for (let i = 0; i < this.length; i++) {
// Determine whether there is a second parameter
if (obj === undefined) {
flag = callback(arr[i], i);
judge(flag,arr[i]);
} else if (typeof obj === "object") {
// 将 this 指向挂到 obj 上
flag = callback.call(obj, arr[i], i);
judge(flag,arr[i]);
}
}
return newArr;
}
Array.prototype.each = each;
// test
let arr = [10, 20, 30, 'AA', 40];
let obj = {};
arr = arr.each(function(item, index){
// obj
this[index] = item;
if (isNaN(item)) return false;
return item * 10;
},obj)
console.log(arr); // [100, 200, 300, 'AA', 400]
console.log(obj); // {0: 10, 1: 20, 2: 30, 3: "AA", 4: 40}
公众号:Coder 杂谈,欢迎关注