Array.map和Javascript中的提升函数 [英] Array.map and lifted functions in Javascript
问题描述
如何
var a =foo / bar / baz.split('/');
a.map(function(e){return String.prototype.trim.call(e)})
可以工作,但这不... ...
a.map(String.prototype .trim);
试试这个:
a.map(Function.prototype.call.bind(String.prototype.trim))
这个工作原理和映射 String.prototype.trim
不起作用的原因是因为像其他人一样指出,当函数试图修剪数组元素时, this
将是未定义的。该解决方案所做的是创建一个新函数,该函数将这个
值作为函数 String.prototype.trim
。由于新函数是 Function.prototype.call
的修改版本,因为 map
调用此函数将数组传递给它元素,本质上得到执行的是: Function.prototype.call.call(String.prototype.trim,element)
。这对传入的元素运行函数 String.prototype.trim
,并获得修剪结果。
这也是可行的:
a.map(Function.call,.trim)
利用第二个参数 map
接受 thisArg
。
对于一点点语法糖,您可以创建如下所示的函数:
Array.prototype。 mapUsingThis = function(fn){return this.map(Function.call,fn); };
然后,您可以调用
a.mapUsingThis(。trim)
就是这样。
How come
var a = "foo / bar/ baz ".split('/');
a.map( function (e) { return String.prototype.trim.call(e) } )
works, while this doesn't...
a.map( String.prototype.trim );
Try this:
a.map(Function.prototype.call.bind(String.prototype.trim ))
The reason why this works and just mapping String.prototype.trim
doesn't work is because, as others have pointed out, the this
will be undefined when the function tries to trim the array element. What this solution does is, it creates a new function, which takes as it's this
value as the function String.prototype.trim
. Since the new function is a modified version of Function.prototype.call
, as map
calls this function passing it the array element, what essentially gets executed is: Function.prototype.call.call(String.prototype.trim, element)
. This runs the function String.prototype.trim
on the element passed in and you get the trimmed result.
This also would work:
a.map(Function.call, "".trim)
by taking advantage of the fact that the second argument to map
accepts the thisArg
.
For a little bit of syntactic sugar, you can make a function that looks like this:
Array.prototype.mapUsingThis = function(fn) { return this.map(Function.call, fn); };
Then, you could just invoke
a.mapUsingThis("".trim)
like that.
这篇关于Array.map和Javascript中的提升函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!