Metoda JavaScript Function apply () volá funkci s danou touto hodnotou a argumenty poskytované jako pole.
Syntaxe apply()
metody je:
func.apply(thisArg, argsArray)
Tady func
je funkce.
použít () parametry
apply()
Metoda bere v:
thisArg
- Hodnotathis
poskytovaná pro volánífunc
.argsArray
(nepovinné) - Objekt typu Array obsahující argumenty funkce.
Vrátit hodnotu z apply ()
- Vrátí výsledek volání funkce se zadanou
this
hodnotou a argumenty.
Použitím apply()
můžeme použít vestavěné funkce pro nějaký úkol, který by jinak pravděpodobně vyžadoval smyčku přes hodnoty pole.
Příklad: Použití apply () s integrovanými funkcemi
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' )
Výstup
8 8 ('a', 'b', 'c', 'd', 'e') ('a', 'b', 'c', 'd', 'e')
Doporučené čtení: Volání funkce JavaScriptu ()