首页  >  问答  >  正文

交换两个值的数组解构赋值无法实现,不使用分号(;)

<p><br /></p> <pre class="brush:php;toolbar:false;">let [x, y] = [10, 20] [y, x] = [x, y] console.log(x, y)</pre> <p>它没有按预期工作,给了我一个错误...</p> <blockquote> <p>Uncaught ReferenceError: Cannot access 'y' before initialization</p> </blockquote> <pre class="brush:php;toolbar:false;">let [x, y] = [10, 20]; // 在这里使用分号 [y, x] = [x, y] console.log(x, y)</pre> <p>现在它可以正常工作,请有谁可以解释为什么它现在可以工作...</p>
P粉714780768P粉714780768437 天前426

全部回复(1)我来回复

  • P粉212971745

    P粉2129717452023-08-11 12:51:28

    首先你需要先声明 x 和 y,而且在一行的语句后需要使用分号。

    let x, y; [x, y] = [10, 20]; [y, x] = [x, y]; console.log(x, y)

    编辑:对不起,你不需要事先声明它们,但是在指令之间要使用分号进行分隔。

    回复
    0
  • 取消回复