web-interview
web-interview copied to clipboard
[选择题] 51.(单选题)下面代码的输出是什么
function sum(numl, num2 = numl) {
console.log(numl + num2)
}
sum(10)
A:NaN
B: 20
C: ReferenceError
D: undefined
答案:B
解析:
您可以将默认参数的值设置为函数的另一个参数,只要另一个参数定义在其之前即可。我们将值10传递给sum函数。如果sum函数只接收1个参数,则意味看没有传递 num2 的 值 . 这 种 情 况 下 的 值 等 于 传 递 的 值 10。num2 的默认值是num1 的值,即10 。 num1 + num2 返回 20。
如果您尝试将默认参数的值设置为后面定义的参数,则可能导致参数的值尚未初始化,从而引发错误。比如:
function test(m = n, n = 2) {
console.log(m, n)
}
test() // Uncaught ReferenceEmor: Cannot access
test(3) // 3 2
test(3, 4) // 3 4