yisainan / web-interview

我是齐丶先丶森,收集整理全网面试题及面试技巧,旨在帮助前端工程师们找到一份好工作!更多详见公众号「前端面试秘籍」
MIT License
2.61k stars 507 forks source link

[选择题] 51.(单选题)下面代码的输出是什么 #1029

Open qiilee opened 4 years ago

qiilee commented 4 years ago
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