- 输出及原因分析:
- 代码运行时会报错。原因是在函数
testFunction
定义中,默认参数a = b + 1
,这里b
在函数定义时还未声明,JavaScript 中函数的默认参数是在函数定义阶段进行计算的,而不是在函数调用阶段。在定义函数testFunction
时,b
还不存在,所以会报ReferenceError: b is not defined
错误。
- 修正方法:
let b = 5;
function testFunction(a = b + 1, ...rest) {
console.log(a);
console.log(rest);
}
testFunction(10, 20, 30);
- 这样修改后,函数定义时
b
已经存在,默认参数a = b + 1
可以正确计算。当调用testFunction(10, 20, 30)
时,由于传入了第一个参数10
,所以a
的值为10
,rest
的值为数组[20, 30]
,输出结果为:
10
[20, 30]
function testFunction(...rest) {
let a;
if (rest.length === 0) {
let b = 5;
a = b + 1;
} else {
a = rest[0];
rest.shift();
}
console.log(a);
console.log(rest);
}
testFunction(10, 20, 30);
- 这种情况下,
b
的声明和计算在函数内部,避免了函数定义时b
未声明的问题。输出同样为:
10
[20, 30]