gpt4 book ai didi

javascript - 为什么 ["A","B","C"].map(String.prototype.toLowerCase.call) 不起作用?

转载 作者:行者123 更新时间:2023-12-03 00:47:57 25 4
gpt4 key购买 nike

这当然会返回您所期望的结果:

["A","B","C"].map(function (x) {
return x.toLowerCase();
});
// --> ["a", "b", "c"]

使用 String.prototype.toLowerCase.call 也是如此:

["A","B","C"].map(function (x) {
return String.prototype.toLowerCase.call(x);
});
// --> ["a", "b", "c"]

如果您传递映射给出的额外参数,它也会起作用,因为它会丢弃参数:

["A","B","C"].map(function (x, index, arr) {
return String.prototype.toLowerCase.call(x, index, arr);
});
// --> ["a", "b", "c"]

但是,这不起作用:

["A","B","C"].map(String.prototype.toLowerCase.call);
// --> TypeError: undefined is not a function

以下内容也不起作用,因为 arguments具有对象原型(prototype)而不是数组原型(prototype),因此 slice其上未定义。上述行为的原因是否可能是因为类似的原因 - 其中 slice或者内部使用了其他类似的数组函数?

["A","B","C"].map(function (x) {
return String.prototype.toLowerCase.apply(x, arguments.slice(1));
});
// --> TypeError: undefined is not a function

最佳答案

类似问题:Why won't passing `''.trim()` straight to `[].map()`'s callback work?

Map 有一个可选的 thisArg,可以像这样使用:

['A', 'B', 'C'].map(Function.prototype.call, String.prototype.toLowerCase);  
// gives ["a", "b", "c"]

关于javascript - 为什么 ["A","B","C"].map(String.prototype.toLowerCase.call) 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23280974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com