gpt4 book ai didi

javascript - 如何将原型(prototype)上定义的方法作为回调传递给 Array.map

转载 作者:数据小太阳 更新时间:2023-10-29 04:38:25 25 4
gpt4 key购买 nike

我有一个数组

var arr = [' A ', ' b ', 'c'];

我想 trim 数组中每个元素的空格。

这可以通过使用 Array.map 来完成作为

arr.map(function(el) {
return el.trim();
});

我很好奇将 trim/toLowerCase 函数作为回调函数直接传递给 map,例如 arr.map(Math.max.apply.bind(Math.max, null));从每个子数组或 arr.map(Number); 中获取最大元素将每个元素转换为数字。

我试过了

arr.map(String.prototype.trim.apply);

但是报错

Uncaught TypeError: Function.prototype.apply was called on undefined, which is a undefined and not a function

我希望为数组中的每个元素调用 String.prototype.trim.apply 并将上下文设置为数组中的元素(传递给 apply) ;

我还尝试了 apply 的不同组合, callbind没有成功。

  1. 为什么使用map时无法引用prototype上的函数
  2. 如何函数可以作为参数传递给map

最佳答案

arr.map(String.prototype.trim.call.bind(String.prototype.trim));

call 在内部使用 this,它必须指向 trim 函数才能在这种情况下正常工作。简单地传递 String.prototype.trim.call 将使 call 未绑定(bind)到任何方法,导致 this 值指向 window 代替。

It works, but when used apply instead of call it throws error, arr.map(String.prototype.trim.apply.bind(String.prototype.trim));

问题是 map 将传递 2 个参数,项目和索引。因此,它最终会调用类似 'String.prototype.trim.apply('test', 0) 的方法,但由于第二个参数必须是数组而失败。

one more thing [' A ', ' B ', 'c'].map(String.prototype.trim.call.bind(String.prototype.toLowerCase));, in this, I've used trim.call and passed toLowerCase as context then why we need trim here, why trim is not called

当使用 call.bind 时,您选择访问 call 函数引用的路径变得无关紧要。将被调用的函数是绑定(bind)的函数。

如果你想将函数组合在一起,你需要一种不同的方法:

var call = Function.prototype.call,
trim = call.bind(String.prototype.trim),
toLowerCase = call.bind(String.prototype.toLowerCase),
trimAndLowerCase = pipelineFrom(trim, toLowerCase);

[' TeST '].map(trimAndLowerCase);

function pipelineFrom(fn1, fn2) {
return function (val) {
return fn2(fn1(val));
};
}

然而在这一点上你最好:

arr.map(function (val) {
return val.trim().toLowerCase();
});

关于javascript - 如何将原型(prototype)上定义的方法作为回调传递给 Array.map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33006222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com