在Python中,你可以这样做:
>>> list(map(str.upper, ['foo','bar']))
['FOO', 'BAR']我希望能够在javascript中做类似的事情:
我已经使用原生地图实现( https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map )在Chrome中尝试了以下功能:
['foo','bar'].map(String.prototype.toUpperCase)
['foo','bar'].map(String.prototype.toUpperCase.call)为什么不打电话给工作呢?有没有什么很好的方法可以做到这一点,或者我必须把toUpperCase包装在一个回调函数中?Thx
发布于 2010-11-13 02:34:17
现代浏览器支持这一点(although it is a recent addition)
var a = ['foo','bar'];
var b = a.map(String.toUpperCase);
alert(b[1]);甚至是
var a = ['foo','bar'].map(String.toUpperCase);
alert(a[0]);发布于 2012-11-10 21:41:22
尝试:
['foo','bar'].map(Function.prototype.call.bind(String.prototype.toUpperCase))或者为了同样的效果:
['foo','bar'].map(Function.call.bind("".toUpperCase))JavaScript对this的处理是一次糟糕的旅行。
发布于 2010-11-13 02:37:50
这是因为String.prototype.toUpperCase在this ( context )对象上运行,但是map函数不能将数组元素设置为context。它将其作为参数传递。一种解决方法是
['foo','bar'].map(function(k) { return String.prototype.toUpperCase.call(k) });https://stackoverflow.com/questions/4167854
复制相似问题