javascript - 为什么不传递 `' '.trim( )` straight to ` [].map( )`' 的回调工作?

标签 javascript

我有一个字符串数组。我想 trim 数组中的每个字符串。

我想使用 [].map()''.trim()会工作...

[' a', ' b   ', 'c'].map(String.prototype.trim);

...但是我的控制台说...

TypeError: String.prototype.trim called on null or undefined

jsFiddle .

我在数组中看不到任何 nullundefined 值。

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.callString.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/

相关文章:

javascript - Angularfire在$push后获得唯一的id

javascript - 如何为这样的对象定义 JSDoc?

javascript - 为什么使用 "call"调用数组切片方法?

javascript - 将\n 或\r 更改为 <br/>

javascript - 为项目使用 "base"存储库?

javascript - 为什么我的 Backbone.js 错误回调被调用,即使 Rails 应该返回成功响应?

javascript - map 框适合国家/地区

javascript - jQuery 滚动和 anchor 初始位置

javascript - 这个算法的时间和空间复杂度是O(n)还是O(1)?

javascript - 在 Javascript 中交换字符串的单词