Javascript - 将修剪功能应用到数组中的每个字符串 [英] Javascript - Apply trim function to each string in an array
问题描述
想要修饰数组中的每个字符串,例如给出
x = ['aa','bb'] ;
输出
['aa','bb']
我的第一个试验是
x.map(String.prototype.trim.apply)
在铬中获得TypeError:Function.prototype.apply被调用未定义,这是一个未定义的函数,而不是函数。
然后我尝试了
x.map(function(s){return String.prototype.trim.apply(s) ;});
有效。 Function.prototype.apply
方法,而不被绑定到 trim
。 map
将用字符串,索引和数组作为参数来调用它,并且 undefined ) / zh-CN / docs / Web / JavaScript / Reference / Operators / this> this
Arg - 但是, apply
期望在函数上调用:
var apply = String.prototype.trim.apply;
apply.call(undefined,x [0],0,x)// TypeError
你可以做的是传递 trim
函数作为调用
的上下文:
['aa','bb'] .map(Function.prototype.call,String.prototype.trim)
// ['aa' ,'bb']
这里发生的是
var call = Function.prototype.call,
trim = String.prototype.trim;
call.call(trim,x [0],0,x)≡
trim.call(x [0],0,x)≡
x [0] .trim(0, X); //参数无关紧要
Want to trim each string in an array, e.g., given
x = [' aa ', ' bb '];
output
['aa', 'bb']
My first trial is
x.map(String.prototype.trim.apply)
It got "TypeError: Function.prototype.apply was called on undefined, which is a undefined and not a function" in chromium.
Then I tried
x.map(function(s) { return String.prototype.trim.apply(s); });
It works. What's the difference?
String.prototype.trim.apply
is the Function.prototype.apply
method without being bound to trim
. map
will invoke it with the string, the index and the array as arguments and nothing (undefined
) for the this
Arg - however, apply
expects to be called on functions:
var apply = String.prototype.trim.apply;
apply.call(undefined, x[0], 0, x) // TypeError
What you can do is passing the trim
function as the context for call
:
[' aa ', ' bb '].map(Function.prototype.call, String.prototype.trim)
// ['aa', 'bb']
What happens here is
var call = Function.prototype.call,
trim = String.prototype.trim;
call.call(trim, x[0], 0, x) ≡
trim.call(x[0], 0, x) ≡
x[0].trim(0, x); // the arguments don't matter to trim
这篇关于Javascript - 将修剪功能应用到数组中的每个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!