参考原文:地址
实现很简单:
<script type="text/javascript">
let arr = [21,3,1,4,23];
let max = Math.max.apply(null,arr); //获取最大值
let min = Math.min.apply(null,arr); //获取最小值
console.log(max,min); //打印输出为23和1
</script>
-
XXX.apply是一个调用函数的方法,其参数为:apply(Function, Args),
-
Function为要调用的方法,Args是参数列表,当Function为null时,默认为上文,
-
即
-
Math.max.apply(null, arr)
-
可认为是
-
apply(Math.max, arr)
-
然后,arr是一个参数列表,对于max方法,其参数是若干个数,即
-
Math.max(a, b, c, d, ...)
-
当使用apply时,把所有参数加入到一个数组中,即
扫描二维码关注公众号,回复: 5664324 查看本文章 -
arr = [a, b, c, d, ...]
-
代入到原式,
-
Math.max.apply(null, [a, b, c, d, ...])
-
实际上等同于
-
Math.max(a, b, c, d, ...)
-
在此处,使用apply的优点是在部分JS引擎中提升性能。
巴拉巴拉: