【发布时间】:2014-04-24 22:25:22
【问题描述】:
当然,这会返回您所期望的:
["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"]
如果你传递 map 给出的额外参数,它也可以工作,因为它会丢弃参数:
["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 具有 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
【问题讨论】:
-
您将
call函数传递给map,它与['A','B','C'].map(Function.prototype.call)相同,您希望以在每个元素上调用String.prototype.toLowerCase函数的方式传递数组。 -
执行此操作的正确方法是代码中的第一个示例。
标签: javascript