【发布时间】:2015-01-14 10:14:27
【问题描述】:
而不是一个问题,我只是希望它是一个挑战,但还没有找到答案。
例如,我们有一个字符串数组
x = ['a', ' b', ' c ']
我想修剪所有元素。我尝试了apply 和call 方法,但都没有按预期工作:
x.forEach(String.prototype.trim.call)
// Uncaught TypeError: undefined is not a function
x.forEach(String.prototype.trim.apply)
// Uncaught TypeError: Function.prototype.apply was called on undefined, which is a undefined and not a function
这里发生了什么? apply/call 应该从每个函数中获取他们的第一个参数,一切看起来都很好。
【问题讨论】:
-
这是一个类静态方法的好例子:
String.trim = function(s) { return s.trim() }; x = x.map(String.trim) -
@thefourtheye:你为什么认为它是重复的?
-
@Guffa 这显然是个骗子。不幸的是,
.map和.forEach的规范不允许将当前元素作为this传递,这与 jQuery 等效项不同。 -
@Guffa 作为操作我确认这是重复的。请参阅已接受答案中的 cmets。作者问的和我问的一样。
-
好吧,我没有深入了解它。我只是对这显然不是问题本身的重复这一事实作出反应。
标签: javascript prototype declarative-programming