Math.max.apply()如何工作? [英] How does the Math.max.apply() work?
问题描述
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
上面的代码找到列表中的最大数量。谁能告诉我下面的代码是如何工作的?如果我传递 null或Math。
控制台,它似乎可以工作。日志(Math.max.apply(数学,列表));
所有用户定义的/ Native函数
有调用和应用方法,我们可以使用它。
apply
接受一个数组,并将该数组作为参数应用于实际函数。所以,
Math.max.apply(Math,list);
可以理解为,
<$ p $ Math.max(12,23,100,34,56,9,233);
因此, apply
是一种方便的方式将一组数据作为参数传递给函数。记住
console.log(Math.max(list)); #NaN
将不起作用,因为 max
不接受数组作为输入。
使用 apply
还有另一个好处,您可以选择您的自己的环境。第一个参数,你传给任何函数的 apply
,将会是该函数中的 this
。但是, max
不依赖于当前上下文。因此,任何事情都可以在 Math
。
控制台中运行。 log(Math.max.apply(undefined,list)); #233
console.log(Math.max.apply(null,list)); #233
console.log(Math.max.apply(Math,list)); #233
自 apply 实际上定义在
,任何有效的JavaScript函数对象,默认都会有 Function.prototype
apply
函数。
How does the Math.max.apply()
work?.
<!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
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
accepts an array and it applies the array as parameters to the actual function. So,
Math.max.apply(Math, list);
can be understood as,
Math.max("12", "23", "100", "34", "56", "9", "233");
So, apply
is a convenient way to pass an array of data as parameters to a function. Remember
console.log(Math.max(list)); # NaN
will not work, because max
doesn't accept an array as input.
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
Since apply
is actually defined in Function.prototype
, any valid JavaScript function object, will have apply
function, by default.
这篇关于Math.max.apply()如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!