Open fedono opened 1 year ago
这里的重点是,你自定义之后的传参,以及如何返回
Array.prototype.myMap = function (callback, thisObj) {
const result = [];
this.forEach((...args) => {
const index = args[1];
result[index] = callback.apply(thisObj, args);
});
return result;
};
const arr = [1, 2, 3];
const res = arr.myMap((curr, id, array) => {
console.log(curr, id, array);
return curr + 1;
});
console.log(res);
通过 es 标准实现
// Based on ECMAScript spec https://262.ecma-international.org/6.0/#sec-array.prototype.map
Array.prototype.myMap = function(callback, ...args) {
let thisObject = Object(this)
if(!thisObject) {
throw new TypeError("this is null")
}
if(typeof callback !== "function"){
throw new TypeError(callback + " is not a function")
}
let length = thisObject.length, mapped = new Array(length)
let thisParameter = args.length ? args[0] : undefined
for(let i = 0; i < length; i++){
// Handle sparse array
if(i in thisObject){
// support this binding
mapped[i] = callback.call(thisParameter, thisObject[i], i, thisObject)
}
}
return mapped
}