Metoda JavaScript Function apply () prikliče funkcijo z dano to vrednostjo in argumente kot matriko.
Sintaksa apply()
metode je:
func.apply(thisArg, argsArray)
Tukaj func
je funkcija.
apply () Parametri
apply()
Metoda je v:
thisArg
- Vrednost,this
predvidena za klicfunc
.argsArray
(neobvezno) - Array podobnemu objektu, ki vsebuje argumente funkcije.
Vrnjena vrednost iz apply ()
- Vrne rezultat klica funkcije z navedeno
this
vrednostjo in argumenti.
Z uporabo apply()
lahko vgrajene funkcije uporabimo za nekatera opravila, ki bi sicer zahtevala pregledovanje vrednosti polja.
Primer: Uporaba apply () z vgrajenimi funkcijami
const numbers = (5, 1, 4, 3, 4, 6, 8); let max = Math.max.apply(null, numbers); console.log(max); // 8 // similar to let max1 = Math.max(5, 1, 4, 3, 4, 6, 8); console.log(max1); // 8 let letters = ("a", "b", "c"); let other_letters = ("d", "e"); // array implementation for (letter of other_letters) ( letters.push(letter); ) console.log(letters); // ( 'a', 'b', 'c', 'd', 'e' ) letters = ("a", "b", "c"); // using apply() letters.push.apply(letters, other_letters); console.log(letters); // ( 'a', 'b', 'c', 'd', 'e' )
Izhod
8 8 ("a", "b", "c", "d", "e") ("a", "b", "c", "d", "e")
Priporočeno branje: klic funkcije JavaScript ()