Math.max.apply() 如何工作? [英] How does the Math.max.apply() work?

查看:18
本文介绍了Math.max.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数.谁能告诉我下面的代码是如何工作的?如果我通过 null 或 Math.

The above code finds the Max number in the List. Can anyone tell me how does the below code work?. It seems it works if i pass null or Math.

console.log(Math.max.apply(Math,list));

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

Does all the user-defined/Native functions have call and apply method which we can use?.

推荐答案

apply 接受一个数组并将该数组作为参数应用到实际函数中.所以,

apply accepts an array and it applies the array as parameters to the actual function. So,

Math.max.apply(Math, list);

可以理解为,

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

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

So, apply is a convenient way to pass an array of data as parameters to a function. Remember

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

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

will not work, because max doesn't accept an array as input.

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

There is another advantage, of using apply, you can choose your own context. The first parameter, you pass to apply of any function, will be the this inside that function. But, max doesn't depend on the current context. So, anything would work in-place of 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 实际上是在Function.prototype,任何有效的 JavaScript 函数对象,默认都会有 apply 函数.

Since apply is actually defined in Function.prototype, any valid JavaScript function object, will have apply function, by default.

这篇关于Math.max.apply() 如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆