获取数组中的最大值和最小值

一种巧妙的方法获取获取数组中的最大值和最小值。

var numbers = [34, 789, -109 , 200]; 
Math.max.apply(Math, numbers);   //789   
Math.max.call(Math, 34, 789, -109 , 200); //789

// ES6
Math.max.call(Math, ...numbers); // 789

为什么可以这么用,因为数组 numbers 本身没有 max方法,但是 Math有,所以这里就是借助 call / apply 使用 Math.max 方法。

call() 和 apply()都可以改变this的指向,call() 和 apply()的区别在于,call()方法接受的是若干个参数的列表,而apply()方法接受的是一个包含多个参数的数组。

猜你喜欢

转载自blog.csdn.net/weixin_45032067/article/details/125435370