抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >
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);
// [1, 10]
// undefined

test.apply(null, array);
// 1
// 10

var test = {
func: function (a, b) {
console.log(a);
console.log(b);
}
}
const array = [1, 10];
test.func(array);
// [1, 10]
// undefined
test.func.apply(test.func, array);
test.func.apply(null, array);
// 1
// 10

const array = [1, 2, 4, 6, 2, 8];
Math.max(array);
// NaN
const array = [1, 2, 4, 6, 2, 8];
Math.max.apply(null, array);
// 8
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);
// 1
// 10

var test = {
func: function (a, b) {
console.log(a);
console.log(b);
}
}
const array = [1, 10];
test.func(...array);
// 1
// 10

const array = [1, 2, 4, 6, 2, 8];
Math.max(...array);
// 8
使用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);
// 1 12 5
test(1,12,3,4,5);
// 1 12 3 4 5

评论