js中apply和Math.max()函式的使用分析
阿新 • • 發佈:2019-01-31
var arr = [1,4,5,9];
console.log(Math.max.apply(null,arr));
console.log(Math.max.call(Math, arr[0], arr[1], arr[2], arr[3]));
console.log(Math.max(arr[0], arr[1], arr[2], arr[3]));
這裡輸出9,這裡做出簡單的解釋:
Math.max()方法,支援傳遞多個引數,比如:Math.max(1,4,5,2,9)
但是它不支援直接傳遞一個數組作為引數,比如:Math.max(new Array(1,4,5,2,9))。
XXX.apply是一個呼叫函式的方法,其引數為:apply(Function, Args),
Math.max.call可以呼叫任意個引數;
Math.max.apply(null, arr)
可認為是 apply(Math.max, arr)然後,arr是一個引數列表,對於max方法,其引數是若干個數,即
Math.max(a, b, c, d, ...)
當使用apply時,把所有引數加入到一個數組中,即arr = [a, b, c, d, ...]
代入到原式,
Math.max.apply(null, [a, b, c, d, ...])
實際上等同於
Math.max(a, b, c, d, ...)
在此處,使用apply的優點是在部分JS引擎中提升效能。