【问题标题】:Someone please explain the Function.apply.bind(Math.max, null) algorithm有人请解释一下 Function.apply.bind(Math.max, null) 算法
【发布时间】:2018-02-28 20:21:54
【问题描述】:

假设我们有这段代码

function largestOfFour(arr) {
  return arr.map(Function.apply.bind(Math.max, null));
}

其中 arr 是一个数组数组。

  1. 首先,为什么我必须使用 apply()?

我知道当使用方法 Math.max() 对数组进行操作时,我还必须添加 apply() 方法。所以我会有这样的东西Math.max.apply(null, arr)为什么? apply() 是做什么的?

  1. 在这段代码arr.map(Function.apply.bind(Math.max, null)) 中,bind() 究竟做了什么?

请给出我能理解的解释,我真的很感激。

【问题讨论】:

  • 用自己的属性绑定重新创建函数,如果你已经使用了事件可以重新创建......等等......

标签: javascript


【解决方案1】:

查看整个表达式:

arr.map(Function.apply.bind(Math.max, null));

map 期望它的第一个参数是一个函数,它由以下方式返回:

Function.apply.bind(Math.max, null);

Function.applyFunction.prototype.apply 的较短版本。

对其调用 bind 会返回一个特殊版本的 apply,其 this 设置为 Math.max 并且当被调用时,它的第一个参数(即通常用作 this 的值)设置为 null,因为它不会被使用。

所以 arr 中的每个元素都会被有效地调用:

Math.max.apply(null, member);

apply的使用是指将member中的值作为参数传递,好像:

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]
);

【讨论】:

  • 非常感谢您的回答。谢谢。为什么 apply() 必须将 null 作为参数,然后 member. 为什么不只是成员?
【解决方案2】:

Function.apply.bind(Math.max, null) 在调用时创建一个函数定义,默认情况下将null 作为第一个参数,任何提供的参数都将位于第二个。因此,作为对arr.map 的回调,此函数(由于bind 语句)将绑定到Math.max 但是Function.apply 的第一个参数将是null,第二个参数将成为子数组项主数组(其中的项目将作为参数传递给Math.max 函数)。

这是一个古老的技巧,在 ES6 术语中 arr.map(s => Math.max(...s)); 会更清楚地完成相同的工作。

【讨论】:

    【解决方案3】:

    简单地说,.apply 调用一个函数,并将一组参数(类似数组)传递给它。

    EG:

    const add = (...args) => args.reduce((acc, next) => acc + next);
    

    我可以像这样使用.apply 方法调用带有任意数量参数的add 函数。

    add.apply(null, [4, 2, 6, 76, 9]) // => 97.
    

    你调用也使用.call,但是你不需要传入类似数组的参数,你只需传入值

    add.call(null, 4, 2, 6, 76, 9) // => 97.
    

    使用.bind,不同之处在于它创建了一个新函数,稍后调用。

    const addFunc = add.bind(null, 4, 2, 6, 76, 9);
    addFunc() // -> 97.
    

    因此,它适用于我们定义的函数,也适用于 Math.maxMath.min 等内置函数。

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-27
      • 2013-05-21
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多