apply()方法使用給定的this值調(diào)用一個函數(shù),并以數(shù)組(或類似數(shù)組的對象)的形式提供參數(shù)。
let numbers = [5, 6, 2, 3, 7]; let max = Math.max.apply(null, numbers); document.write(max);測試看看?/?
call()方法單獨(dú)接受參數(shù)。
apply()方法將參數(shù)作為數(shù)組。
如果要使用數(shù)組而不是參數(shù)列表,則apply()方法非常方便。
巧妙地使用,apply()您可以將內(nèi)置函數(shù)用于某些任務(wù),否則可能是通過遍歷數(shù)組值來編寫的。
作為示例,我們將使用Math.max/ Math.min來找出數(shù)組中的最大值/最小值。
let numbers = [5, 6, 2, 3, 7];
let max = Math.max.apply(null, numbers);
let min = Math.min.apply(null, numbers);
for(let i = 0; i < numbers.length; i++) {
if(numbers[i] > max) {
max = numbers[i];
}
if(numbers[i] < min) {
min = numbers[i];
}
}
document.write(min, "<br>", max);測試看看?/?在下面的示例中,我們在不傳遞參數(shù)的情況下調(diào)用了display函數(shù):
var name = "Seagull";
function display() {
document.write(this.name);
}
display.apply();測試看看?/?