当然,这会返回您的期望:
["A","B","C"].map(function (x) {
return x.toLowerCase();
});
// --> ["a", "b", "c"]
Run Code Online (Sandbox Code Playgroud)
使用String.prototype.toLowerCase.call也是如此:
["A","B","C"].map(function (x) {
return String.prototype.toLowerCase.call(x);
});
// --> ["a", "b", "c"]
Run Code Online (Sandbox Code Playgroud)
如果你传递map给出的额外参数,它也会起作用,因为它抛弃了参数:
["A","B","C"].map(function (x, index, arr) {
return String.prototype.toLowerCase.call(x, index, arr);
});
// --> ["a", "b", "c"]
Run Code Online (Sandbox Code Playgroud)
但是,这不起作用:
["A","B","C"].map(String.prototype.toLowerCase.call);
// --> TypeError: undefined is not a function
Run Code Online (Sandbox Code Playgroud)
以下也不起作用,因为arguments具有Object原型而不是Array原型,因此slice未定义它.上述行为的原因可能是因为这样的事情 - 在slice内部使用哪里或其他类似的Array函数?
["A","B","C"].map(function (x) {
return String.prototype.toLowerCase.apply(x, arguments.slice(1));
});
// --> TypeError: undefined is not a function
Run Code Online (Sandbox Code Playgroud)
Dec*_*ook 26
类似的问题:为什么不将`''.terim()`直接传递给`[] .map()`的回调工作?
Map有一个可选的thisArg,可以这样使用:
['A', 'B', 'C'].map(Function.prototype.call, String.prototype.toLowerCase);
// gives ["a", "b", "c"]
Run Code Online (Sandbox Code Playgroud)
Kee*_*een 13
这是JavaScript的点符号的特殊行为.
toLowerCase.call(x)是工作,因为JavaScript使用toLowerCase如this在执行call.这就是call(Function.prototype.call你在每个函数上找到的)知道你想要它执行的方式toLowerCase.
传递call到另一个函数的损失,损失的参考,所以this不再引用toLowerCase.
问题是String.prototype.toLowerCase.call == Function.prototype.call.如果你想获得一个将参数转换为小写的toLowerCase函数,你可以将函数绑定到函数call:
var toLowerCase = String.prototype.toLowerCase.call.bind(String.prototype.toLowerCase);
["A","B","C"].map(toLowerCase);
Run Code Online (Sandbox Code Playgroud)