我有一个字符串数组。我想 trim 数组中的每个字符串。
我想使用 [].map()
与 ''.trim()
会工作...
[' a', ' b ', 'c'].map(String.prototype.trim);
...但是我的控制台说...
TypeError: String.prototype.trim called on null or undefined
jsFiddle .
我在数组中看不到任何 null
或 undefined
值。
String.prototype.trim()
和 Array.prototype.map()
是在我用来测试的 Chrome 17 中定义的。
为什么这行不通?我觉得我忽略了一些明显的东西。
我意识到我可以在其中循环或放置一个函数。然而,这不是这个问题的重点。
最佳答案
@Slace 说的是正确的解释。 @ThomasEding 的答案也有效,但有一个非常低效的问题,即它可能在循环内创建函数,即 not a good thing to do .罢工>
另一种做法是 (reference here) :
[' a', ' b ', 'c'].map(Function.prototype.call, String.prototype.trim);
// gives ["a", "b", "c"]
标准浏览器免责声明:这适用于任何Function.prototype.call
和String.prototype.trim
适用的地方,并且适用于旧版浏览器,您可以轻松地将 trim
替换为 polyfill像这样:
if(!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,'');
};
}
更新:有趣的是,虽然这在 Chrome 中运行最快,@ThomasEding 的方法在 IE10 和 FF20 中运行速度稍快 - http://jsperf.com/native-trim-vs-regex-trim-vs-mixed
关于javascript - 为什么不传递 `' '.trim( )` straight to ` [].map( )`' 的回调工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9304007/