有没有办法使Array.prototype.map成为一个函数,并将其称为customMap(passitanyarray,function)
一般来说,有没有办法获得Array.prototype.(whatever)
并采取任何东西,并使其成为你自己的功能。例如像Array.prototype.map(function())
并提取地图和使用像这个map([],function())
而不是Array.prototype.map(function())
如果不清楚,我会解释更多。
提前致谢
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Polyfill
您可以像这样包装arr.map()
调用:
function map(arr, fn) {
return arr.map(fn);
}
console.log(map([1,2,3], x => x + 1));
如果您愿意使用该函数管理this
的正确上下文,您可以提取call()
函数并为其提供正确的上下文。它有点难看(而且我不确定它是否明智),但它的工作原理甚至可以与polyfill一起使用:
let arr = [1, 2, 3]
/* get reference to properly bound call() */
let map = Function.call.bind(Array.prototype.map)
/* now you can use it like a regular function */
let double = map(arr, item => item * 2)
console.log(double)