提示:内容虽少,但是里面也有好几个知识点。
step 1:实现函数
function mapTmp (fn){
if(!Array.isArray(this)) return [];
const arr = [];
this.forEach((item, index) => {
const newItem = fn(item, index, this);
arr.push(newItem);
});
return arr;
}
Array.prototype.mapTmp = mapTmp;
step 2:挂在数组原型对象上面
Array.prototype.mapTmp = mapTmp;
step 3:测试
const arr = [1, 2, 3, 4, 5];
arr.mapTmp(item => item + 1); // [2, 3, 4, 5, 6]