前端JS获取数组中的最大值和最小值

参考原文:地址

实现很简单:

<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>
  1. XXX.apply是一个调用函数的方法,其参数为:apply(Function, Args),

  2. Function为要调用的方法,Args是参数列表,当Function为null时,默认为上文,

  3. Math.max.apply(null, arr)

  4. 可认为是

  5. apply(Math.max, arr)

  6. 然后,arr是一个参数列表,对于max方法,其参数是若干个数,即

  7. Math.max(a, b, c, d, ...)

  8. 当使用apply时,把所有参数加入到一个数组中,即

  9. arr = [a, b, c, d, ...]

  10. 代入到原式,

  11. Math.max.apply(null, [a, b, c, d, ...])

  12. 实际上等同于

  13. Math.max(a, b, c, d, ...)

  14. 在此处,使用apply的优点是在部分JS引擎中提升性能。

巴拉巴拉:

==主页传送门==

猜你喜欢

转载自blog.csdn.net/weixin_42941619/article/details/88817380
今日推荐