一种巧妙的方法获取获取数组中的最大值和最小值。
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()
方法接受的是一个包含多个参数的数组。