了解 apply 传入参数机制
//模拟 Math.max 方法
function Math_max(num1, num2, num3) {
console.log(num1)
console.log(num2)
console.log(num3)
}
var arr = [36, 27, 59]
// 当直接传入数组的时候,输出 [36, 27, 59] undefined undefined 相当于传入一个参数
Math_max(arr)
// 当调用 apply 方法后,输出 36,27, 59, 相当于传入三个参数
Math_max.apply(null, arr)
apply 方法的最主要的作用是改变当前函数的 this 指向,还有一个作用就是将数组中的元素一个一个的当做参数传入方法,apply 方法和 call 方法基本相同, 此处 Math_max.apply(null, arr) 和Math_max.apply(null, 36, 27, 59) 相同, 所以当我们调用 apply 方法的时候,相当于把数组中的元素挨个当做参数传入方法中,这也就解决了 Math.max(min) 不能直接获取数组中的最大(小)值问题了
改变 this 指向对 Math.max(min).apply 无影响
function foo() {
//someFunction
}
var o = {
//someProperty
}
var values = [10, 20, 50, 14, 21]
// Math.max 函数体内的 this 对象指向 o
var result_1 = Math.max.apply(o, values)
// Math.max 函数体内的 this 对象指向 foo
var result_2 = Math.max.apply(foo, values)
// Math.max 函数体内的 this 对象指向空对象
var result_3 = Math.max.apply(null, values)
console.log(result_1) //50
console.log(result_2) //50
console.log(result_3) //50
用 Math.max(min).apply() 获取数组中的最大(小)值
var arr = [20, 30, 24, 16, 52]
console.log(Math.max.apply(null, arr)) //52
console.log(Math.min.apply(null, arr)) //16
// 此处 apply() 方法的第一个参数可以是 null, 可以是数组、对象、方法