apply可以改变函数的this指向(类似的还有call和bind),且函数的输入参数需要是一个数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| function test(a, b) { console.log(a); console.log(b); } const array = [1, 10]; test(array);
test.apply(null, array);
var test = { func: function (a, b) { console.log(a); console.log(b); } } const array = [1, 10]; test.func(array);
test.func.apply(test.func, array); test.func.apply(null, array);
const array = [1, 2, 4, 6, 2, 8]; Math.max(array);
const array = [1, 2, 4, 6, 2, 8]; Math.max.apply(null, array);
|
ES6中的扩展符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| function test(a, b) { console.log(a); console.log(b); } const array = [1, 10]; test(...array);
var test = { func: function (a, b) { console.log(a); console.log(b); } } const array = [1, 10]; test.func(...array);
const array = [1, 2, 4, 6, 2, 8]; Math.max(...array);
|
使用arguments对象(不建议使用)
函数内的arguments对象,其本身是由给函数传入的参数,以类似数组的形式组合而成的对象。
1 2 3 4 5 6 7 8 9
| function test() { for (let i = 0; i < arguments.length; i++) { console.log(arguments[i]); } } test(1,12,5);
test(1,12,3,4,5);
|