English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The apply() method calls a function with the given this value and provides parameters in the form of an array (or an object similar to an array).
let numbers = [5, 6, 2, 3, 7]; let max = Math.max.apply(null, numbers); document.write(max);Test and See‹/›
The call() method accepts parameters separately.
The apply() method takes parameters asArray.
If you want to use an array instead of a parameter list, the apply() method is very convenient.
Useful in conjunction with apply(), you can use built-in functions for certain tasks that might otherwise be written by iterating over array values.
As an example, we will use Math.max/ Find the Maximum Value in the Array Using Math.max/Minimum Value.
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);Test and See‹/›
In the following example, we call the display function without passing any parameters:
var name = "Seagull"; function display() { document.write(this.name); } display.apply();Test and See‹/›