//使用 reduce 實現數組 map 方法 const selfMap2 = function (fn, context){ let arr = Array.prototype.slice.call(this) // 這種實現方法和循環的實現方法有異曲同工之妙,利用reduce contact起數組中每一項 // 不過這種有個弊端,會跳過稀疏數組中為空的項 return arr.reduce((pre, cur, index) => { return [...pre, fn.call(context, cur, index, this)] }, []) } Array.prototype.selfMap = selfMap2 var arr1 = [1, 2, 3] arr1.length = 5 let arrMap = arr1.selfMap(function (x) { return x * 2 }) // [2, 4, 6]