以下代码失败:
array.map(String.prototype.toLowerCase)
抛出未捕获的类型错误:在 null 或未定义时调用 String.prototype.toLowerCase
。确实,this
没有设置,我明白了。
但奇怪的是,以下代码返回一个空字符串数组而没有失败:
array.map((s) => String.prototype.toLowerCase(s))
知道为什么吗? 请注意,我知道这不是拥有小写字符串数组的方式。我只是想知道为什么这两种方法的行为不同。
换句话来说,.map(String.prototype.toLowerCase)
和.map((s) => String.prototype.toLowerCase(s))有什么区别
?我认为这是相同的,但显然,它的行为不同。请注意,这里的 String.prototype.toLowerCase
可以替换为任何内容。
最佳答案
What is the difference between
.map(String.prototype.toLowerCase)
and.map((s) => String.prototype.toLowerCase(s))
对于第一种情况,当你在对象之外获取函数时 (String.prototype.toLowerCase)
你失去了你的上下文,所以你的上下文为空并且 map
尝试调用null or undefined
。使用第一个解决方案,您无法获得所需的结果,因为您需要将上下文传递给 toLowerCase
函数,它必须是数组的每一项,但你无法得到数组的每一项。
对于第二种情况,您需要传递上下文,即 item
到String.prototype.toLowerCase
通过call
功能。
var array = ['ASD', 'BSD'];
var lowered = array.map(item => String.prototype.toLowerCase.call(item));
console.log(lowered);
关于javascript - 为什么传递函数引用失败而使用函数声明却失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45838244/