假设我们有这段代码
function largestOfFour(arr) {
return arr.map(Function.apply.bind(Math.max, null));
}
Run Code Online (Sandbox Code Playgroud)
其中arr是一个数组数组。
我知道使用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));
Run Code Online (Sandbox Code Playgroud)
map希望其第一个参数是一个函数,由以下函数返回:
Function.apply.bind(Math.max, null);
Run Code Online (Sandbox Code Playgroud)
Function.apply是一个较短的版本Function.prototype.apply的。
在其上调用bind将返回一个特殊版本的apply,该应用的特殊版本设置为Math.max,并且在调用时将其第一个参数(即通常用作this的值)设置为null,因为不会用过的。
因此,将使用以下命令有效地调用arr中的每个元素:
Math.max.apply(null, member);
Run Code Online (Sandbox Code Playgroud)
使用apply表示成员中的值作为参数传递,就像:
Math.max(member[0],member[1] ... member[n]);
Run Code Online (Sandbox Code Playgroud)
因此,表达式返回每个数组中的最大值。这些值将返回给map,这会将它们放入新数组中。
arr.map(Function.apply.bind(Math.max, null));
Run Code Online (Sandbox Code Playgroud)
并且实际上与以下内容相同:
Function.apply.bind(Math.max, null);
Run Code Online (Sandbox Code Playgroud)
尽管使用了最新功能,但是您可以使用带有rest参数语法的销毁:
Math.max.apply(null, member);
Run Code Online (Sandbox Code Playgroud)