为什么任何对象原型都不能用作forEach回调? [英] Why doesn't any object prototype work as a forEach callback?

查看:117
本文介绍了为什么任何对象原型都不能用作forEach回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想让它成为一个挑战,但还没有找到答案,而不是一个问题.

Rather than a question, I just wanted it to be a challenge but couldn't find an answer yet.

例如,我们有一个字符串数组

For example, we have an array of strings

x = ['a', '   b', '  c  ']

,我想修剪所有元素.我尝试了applycall方法,但均未按预期工作:

and I want to trim all the elements. I tried apply and call methods but neither worked as expected:

x.forEach(String.prototype.trim.call)
// Uncaught TypeError: undefined is not a function

x.forEach(String.prototype.trim.apply)
// Uncaught TypeError: Function.prototype.apply was called on undefined, which is a undefined and not a function

这是怎么回事? apply/call应该从每个函数的第一个参数开始,一切似乎都很好.

What's going on here? apply/call should take their first argument from for each function and everything seems fine.

推荐答案

尝试一下,

x = ['a', '   b', '  c  ']
x.map(function(item) { return item.trim() })

这篇关于为什么任何对象原型都不能用作forEach回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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