Math.max.apply()如何工作?

时间:2014-01-21 10:14:22

标签: javascript function apply

Math.max.apply()如何运作?。

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <script>
      var list = ["12","23","100","34","56",
                                    "9","233"];
      console.log(Math.max.apply(Math,list));    
  </script>
</body>
</html>

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

上面的代码在List中找到Max number。任何人都可以告诉我下面的代码是如何工作的?如果我通过null or Math.

,它似乎有效
console.log(Math.max.apply(Math,list));

所有user-defined/Native functions是否都有我们可以使用的调用和应用方法?

4 个答案:

答案 0 :(得分:111)

apply接受一个数组,它将数组作为参数应用于实际函数。所以,

Math.max.apply(Math, list);

可以理解为,

Math.max("12", "23", "100", "34", "56", "9", "233");

因此,apply是将数据数组作为参数传递给函数的便捷方式。记住

console.log(Math.max(list));   # NaN

不起作用,因为max不接受数组作为输入。

使用apply还有另一个优点,您可以选择自己的上下文。传递给任何函数的apply的第一个参数将是该函数内的this。但是,max不依赖于当前的上下文。因此,任何事情都可以替代Math

console.log(Math.max.apply(undefined, list));   # 233
console.log(Math.max.apply(null, list));        # 233
console.log(Math.max.apply(Math, list));        # 233

由于apply is actually defined in Function.prototype,任何有效的JavaScript函数对象都默认具有apply函数。

答案 1 :(得分:23)

在JavaScript ES6上,只需使用Spread operator

var list = ["12","23","100","34","56","9","233"];
console.log(Math.max(...list));
//                   ^^^ Spread operator 

答案 2 :(得分:15)

  

有谁能告诉我下面的代码是如何工作的?

Math.max.apply(Math,list)

调用带有Math.max对象的Math函数,用作函数实现(正文)中的this引用,并将list作为参数传递。< / p>

所以这最终等于

Math.max("12","23","100","34","56", "9","233")
  

如果我传递null或Math,它似​​乎有效。

显然Math.max实现不使用实例变量 - 没有理由这样做。天真的实现只会迭代arguments并找到最大值。

  

所有用户定义/本机函数是否都有我们可以使用的调用和应用方法?。

是的,可以使用callapply

调用每个功能

参考文献:

答案 3 :(得分:0)

我将首先说Math.max(...numbers)Function.prototype.apply()仅用于元素相对较少的数组。如果数组太大,则(...)和apply将失败或返回错误结果

Math.max.apply(null | undefined | Math, numbers)Math.max(...numbers)相同,因此出于美学原因,我建议使用Math.max(...numbers)

const numbers = [5, 6, 2, 3, 7];

const max = Math.max(...numbers);

console.log('max:', max);
// expected output: 7

const min = Math.min(...numbers);

console.log('min:', min);
// expected output: 2

如果需要在非常大的数字数组中找到最大元素::请使用Array.reduce()方法。

通过比较每个值,

Array.reduce()可用于查找数字数组中的最大元素:

const numbers = [5, 6, 2, 3, 7];
const getMax = (numbers) => numbers.reduce((a, b) => Math.max(a, b));

const getMin = (numbers) => numbers.reduce((a, b) => Math.min(a, b));
	
const max = getMax(numbers)
const min = getMin(numbers)

console.log('max:', max)
console.log('min:', min)

结论:

数值数组相对较小:请使用Math.max(...numbers) 数值数组非常大:使用Array.reduce()方法