Javascript Can';t使用字符串#trim作为数组#map的回调
由于某些原因,我不能使用Javascript Can';t使用字符串#trim作为数组#map的回调,javascript,string,prototype,Javascript,String,Prototype,由于某些原因,我不能使用String.prototype.trim.call作为数组方法的回调,例如map或filter 在这种情况下,两个功能的工作原理相同: function trim(string) { return string.trim(); } var string = ' A '; trim(string); // 'A' String.prototype.trim.call(string); // 'A' 但是,当我尝试将它们
String.prototype.trim.call
作为数组方法的回调,例如map
或filter
在这种情况下,两个功能的工作原理相同:
function trim(string) {
return string.trim();
}
var string = ' A ';
trim(string); // 'A'
String.prototype.trim.call(string); // 'A'
但是,当我尝试将它们作为数组方法的回调传递时,第二个方法失败:
var array = [' A', 'B ', ' C '];
array.map(trim); // ['A', 'B', 'C'];
array.map(String.prototype.trim.call); // TypeError: undefined is not a function
演示:
我假设在后一种情况下,这个
没有指向数组元素,但我想对发生的事情进行清楚的解释
在第一种情况下调用call
方法时,其绑定到String.prototype.trim
函数。在第二种情况下,您只需访问调用
函数,而无需将其绑定到任何东西—您可以使用
array.map(Function.prototype.call)
调用此方法时,将不使用任何内容作为This
值、数组中的元素、索引和整个数组作为参数。当您对函数调用call
时,它会抛出。您可以使用的第二个参数或来修复调用的此值:
array.map(Function.prototype.call, String.prototype.trim)
array.map(Function.prototype.call.bind(String.prototype.trim))
很抱歉,我已经回答了两次:)@Bergi看起来是的,很抱歉。但是,正如你所能想象的,几乎不可能找到一个(老实说,我花了15分钟)。我已经尝试使标题尽可能的笼统和准确。解决这个问题的一个优雅的方法是ES6 arrow函数:array.map(s=>s.trim())代码>。是的,当遇到这个问题时,我知道它是重复的,但找不到它。于是我写了一个答案,后来才发现原来的答案:——)
array.map(Function.prototype.call, String.prototype.trim)
array.map(Function.prototype.call.bind(String.prototype.trim))