ES6默认参数:未正确分配的值

Eri*_*pin 1 javascript default-parameters ecmascript-6

我正在玩ES6默认参数,我有一个奇怪的行为.

以下是该问题的一个简短示例:

function test(firstValue, secondValue=5){
  console.log("firstValue: " + firstValue);
  console.log("secondValue: " + secondValue);
  console.log("----------")
}

test(2, secondValue = 3)
test(secondValue = 3)
Run Code Online (Sandbox Code Playgroud)

它的输出:

firstValue: 2
secondValue: 3
----------
firstValue: 3
secondValue: 5
----------
Run Code Online (Sandbox Code Playgroud)

在第二种情况下,我期待firstValue: undefinedsecondValue: 3.这种行为是否正常.我错过了什么吗?

T.J*_*der 5

当你这样做

test(2, secondValue = 3)
Run Code Online (Sandbox Code Playgroud)

实际上,你是这样做的:

secondValue = 3
test(2, 3)
Run Code Online (Sandbox Code Playgroud)

第一部分(secondValue = 3)创建一个全局变量,secondValue感谢The Impror Globals的恐怖.*它与secondValue函数中的参数无关.JavaScript没有命名参数.(例如,secondValue除了将其置于参数列表中的正确位置之外,您不能说"这里是"的值"."如果要在拨打电话时指定名称,可以使用解构作为cubbuk点out,这不是真正命名的参数,但可以起到同样的作用.)

第二部分(通3test)发生,因为分配的结果是(使得被分配的值secondValue = 3设置secondValue3并且导致值3,然后将其通入test).

要调用test3secondValue,只是这样做.例如:

test(2, 3);
Run Code Online (Sandbox Code Playgroud)

如果要关闭第二个,将使用默认值:

test(2);
Run Code Online (Sandbox Code Playgroud)

例:

function test(firstValue, secondValue=5){
  console.log("firstValue: " + firstValue);
  console.log("secondValue: " + secondValue);
  console.log("----------");
}

test(2, 3);
test(2);
Run Code Online (Sandbox Code Playgroud)


*(这是我贫血的小博客上的帖子)