在浏览JavaScript的功能时,我在同一函数中使用了默认参数和传播语法。

let whatIsThis = (a, b = 2, ...c) => {
    console.log("a = " + a, "b = " + b,"c = " + c)
}

whatIsThis(a = 1, c = [2,3,4,5,6,7,8])


运行它之后,我期望输出是这样的:

"a = 1"
"b = 2"
"c = 2,3,4,5,6,7,8"


但是相反,我得到了这个:

"a = 1"
"b = 2,3,4,5,6,7,8"
"c = "


为什么这没有用?

最佳答案

这是因为您无法将命名参数传递给JavaScript中的函数。当您执行whatIsThis(a = 1,c = [2,3,4,5,6,7,8])时,真正的意思是whatIsThis(1,[2,3,4,5,6,7,8] ])(因为a = 1语句返回1)。

您可以做的是将默认参数移到末尾(通常是一种好习惯),也可以将参数包装在对象中。例如

let whatIsThis = ({a, b = 2, c}) => {
    console.log("a = " + a, "b = " + b,"c = " + c)
}

whatIsThis({a: 1, c: [2,3,4,5,6,7,8]})

10-06 04:49