📜  JavaScript函数apply()

📅  最后修改于: 2020-09-27 06:15:32             🧑  作者: Mango

JavaScript Function apply()方法调用具有给定值的函数 ,并以数组形式提供参数。

apply()方法的语法为:

func.apply(thisArg, argsArray)

在这里, func是一个函数。


apply()参数

apply()方法包含:

  • thisArg为对func的调用提供的this的值。
  • argsArray (可选)-一个类似Array的对象,其中包含该函数的参数。

从apply()返回值
  • 返回使用指定的this值和参数调用函数的结果。

通过使用apply() ,我们可以将内置函数用于某些可能需要循环遍历数组值的任务。

示例:将apply()与内置函数一起使用
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' ]

输出

8
8
[ 'a', 'b', 'c', 'd', 'e' ]
[ 'a', 'b', 'c', 'd', 'e' ]

推荐读物: JavaScript函数call()