为什么不将`''。。(简单)直接传递给`[] .map()`的回调工作? [英] Why won't passing `''.trim()` straight to `[].map()`'s callback work?

查看:121
本文介绍了为什么不将`''。。(简单)直接传递给`[] .map()`的回调工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an array of strings. I want to trim each string in the array.

我想用 []。map() ''。trim() 将起作用...

I thought using [].map() with ''.trim() would work...

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

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

...but my console said...


TypeError:String.prototype.trim调用null或undefined

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

jsFiddle

我看不到任何 null undefined 我的数组中的值。

I can't see any null or undefined values in my array.

String.prototype.trim() Array.prototype.map()在Chrome 17中定义,我正在测试。

String.prototype.trim() and Array.prototype.map() are defined in Chrome 17, which I'm using to test.

为什么这不起作用?我觉得我忽略了一些显而易见的事情。

Why doesn't this work? I get the feeling I have overlooked something obvious.

我意识到我可以在那里循环或删除一个函数。然而,这不是这个问题的重点。

I realise I could loop or drop a function in there. That's not the point of this question, however.

推荐答案

trim 是在 String 原型上,这意味着它希望这个上下文是一个字符串的上下文,其中 map 上的方法> 提供当前数组项作为第一个参数,这个 context是全局对象。

trim is on the String prototype, meaning that it expects the this context to be that of a string where as the map method on Array provides the current array item as the first argument and the this context being the global object.

这篇关于为什么不将`''。。(简单)直接传递给`[] .map()`的回调工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆