对不起,如果我错过了什么,但是当我尝试使用call方法作为回调时,它在Chrome和Node.js中都会给我带来奇怪的错误。
[' foo', ' bar '].map(String.prototype.trim.call);
TypeError: [" foo", " bar "].map is not a function
at Array.map (native)但是这些片段很有用:
[' foo', ' bar '].map(function (item) {
return String.prototype.trim.call(item);
}); // => ['foo', 'bar']
/*
and ES2015
*/
[' foo', ' bar '].map(function () {
return String.prototype.trim.call(...arguments);
}); // => ['foo', 'bar']此外,我还检查了call函数的类型:
typeof String.prototype.trim.call; // => 'function'我做错了什么吗?有人能解释一下我为什么会犯这样的错误吗?谢谢。
发布于 2016-02-09 18:26:03
解决你的问题最简单的方法就是把它写出来:
[' foo', ' bar '].map(s => s.trim());如果您想传递一个函数,您将需要一些比您想要的更复杂的内容,如
.map(Function.call.bind(String.prototype.trim))或者如果你愿意
.map(Function.call, String.prototype.trim)This question可以回答你所有的问题。
https://stackoverflow.com/questions/35299308
复制相似问题