不能使用String#trim作为Array#map的回调 [英] Can't use String#trim as a callback for Array#map
问题描述
出于某种原因,我无法使用 String.prototype.trim.call
作为数组方法的回调,例如 map
或过滤器
。
For some reason I can't use String.prototype.trim.call
as a callback for array methods, such as map
or filter
.
在这种情况下,两个函数的工作方式相同:
In this case, two functions work the same:
function trim(string) {
return string.trim();
}
var string = ' A ';
trim(string); // 'A'
String.prototype.trim.call(string); // 'A'
然而,当我尝试将它们作为数组方法的回调传递时,第二个失败:
However, when I try to pass them as a callback for an array method, second one fails:
var array = [' A', 'B ', ' C '];
array.map(trim); // ['A', 'B', 'C'];
array.map(String.prototype.trim.call); // TypeError: undefined is not a function
演示: http://jsbin.com/ubUHiHon/1/edit?js,console
我假设在后一种情况下这个
没有指向数组元素,但我想清楚地解释发生了什么。
I assume in a latter case that this
doesn't point to an array element, but I would like to get clear explanation of what's happening.
推荐答案
String.prototype.trim.call(string); // 'A'
array.map(String.prototype.trim.call); // TypeError: undefined is not a function
当你调用在第一种情况下调用
方法,其 这个
值绑定到 String.prototype.trim
函数。在第二种情况下,你只需访问调用
函数而不必绑定任何东西 - 你可以使用
When you invoke the call
method in the first case, its this
value is bound to the String.prototype.trim
function. In the second case, you just access the call
function without having it bound to anything - you could just have used
array.map(Function.prototype.call)
this方法被调用,没有任何东西作为这个
值,你的数组中的元素,索引和整个数组作为参数。当您调用调用
而不是某个函数时,它会抛出。您可以使用 <$ C的第二个参数$ C>地图 或在 bind
方法修复此
值 call
:
This method is getting invoked with nothing as the this
value, the element from your array, the index and the whole array as parameters. When you call call
not on a function, it throws. You can either use the second parameter of map
or the bind
method to fix the this
value for the call
:
array.map(Function.prototype.call, String.prototype.trim)
array.map(Function.prototype.call.bind(String.prototype.trim))
这篇关于不能使用String#trim作为Array#map的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!