与不定参数比较相关的是扩展运算符,不定参数将传入的多个参数合并成一个数组,而扩展运算符则是将一个数组拆分单独的元素作为函数的参数传入。
不定参数与扩展运算符做对比
不定参数
// 不定参数function foo (bar, ...rest) {console.log('arguments:', arguments);console.log('bar:', bar);console.log('rest:', rest);}foo(1, 2, 3, 4, 5);
执行结果:
arguments: { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }bar: 1rest: [ 2, 3, 4, 5 ]
扩展运算符
// 扩展运算符function foo (a, b, c) {console.log('arguments', arguments);console.log('a', a);console.log('b', b);console.log('c', c);}const bar = [1, 2, 3];foo(...bar);
执行结果:
arguments { '0': 1, '1': 2, '2': 3 }a 1b 2c 3
