假设我们有这段代码
function largestOfFour(arr) {
return arr.map(Function.apply.bind(Math.max, null));
}
其中 arr 是数组的数组。
- 首先,为什么我必须使用 apply()?
我知道当使用 Math.max() 方法对数组进行操作时,我还必须添加 apply() 方法。所以我会有这样的东西 Math.max.apply(null, arr)
为什么? apply() 是做什么的?
- 在这段代码中
arr.map(Function.apply.bind(Math.max, null))
bind() 到底做了什么?
请给我一个我能理解的解释,我真的很感激。
最佳答案
查看整个表达式:
arr.map(Function.apply.bind(Math.max, null));
map 期望它的第一个参数是一个函数,它由以下函数返回:
Function.apply.bind(Math.max, null);
Function.apply 是 Function.prototype.apply 的较短版本。
对其调用 bind 会返回 apply 的特殊版本,其 this 设置为 Math.max 并且调用时,会将其作为第一个参数(即通常用作 this 的值)设置为 null,因为它不会被使用。
因此 arr 中的每个元素将有效地使用以下方式调用:
Math.max.apply(null, member);
apply 的使用意味着成员中的值作为参数传递,就好像:
Math.max(member[0],member[1] ... member[n]);
因此表达式返回每个数组中的最大值。这些值返回给 map,后者将它们放入一个新数组中。
var arr = [[1,2,3],[4,5,6]];
console.log(
arr.map(Function.apply.bind(Math.max, null)) //[3, 6]
);
并且实际上等同于:
var arr = [[1, 2, 3],[4, 5, 6]];
console.log(
arr.map(function(a) {return Math.max.apply(null, a)}) //[3, 6]
);
尽管使用最近的特性,您可能会使用带有剩余参数语法的解构:
var arr = [[1, 2, 3],[4, 5, 6]];
console.log(
arr.map(a => Math.max(...a)) // [3, 6]
);
关于javascript - 有人请解释 Function.apply.bind(Math.max, null) 算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46310766/