Destructuring assignment in while loop in ES6 function doesn't propogate out of loop?

前端 未结 1 1411
一整个雨季
一整个雨季 2020-12-20 19:44

I was implementing a simple GCD algorithm in ES6 (through node-esml) and came upon (to me) strange behaviour with updating values of variables inside a while loop. This code

相关标签:
1条回答
  • 2020-12-20 20:14

    That's a problem not with destructuring assignment, but with ASI (automatic semicolon insertion). These two lines:

    q = Math.floor(rdash / r)
    [r, rdash] = [rdash - q * r, r]
    

    in practice mean this:

    q = Math.floor(rdash / r)[r, rdash] = [rdash - q * r, r]
    

    which obviously is not what you meant. To fix that, add a semicolon in front of [:

    function gcdWithDestructuredAssignment(x, y) {
      let [r, rdash] = [x, y]
      while (r != 0) {
        q = Math.floor(rdash / r)
        ;[r, rdash] = [rdash - q * r, r]
      }
      return(rdash)
    }
    console.log(gcdWithDestructuredAssignment(97, 34))

    Of course you can add the missing semicolon at the end of the previous line instead (q = Math.floor(rdash / r);), but since you generally don't use semicolons, I assumed that you're using npm coding style.

    0 讨论(0)
提交回复
热议问题