javascript - ES6 函数中 while 循环中的解构赋值不会在循环外传播?

标签 javascript ecmascript-6 destructuring

我在 ES6 中(通过 node-esml)实现了一个简单的 GCD 算法,并且(对我而言)在 while 循环中更新变量值时出现了奇怪的行为。这段代码非常有效:

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

返回 1 的预期答案。但是,如果我删除临时变量并改为使用解构赋值来尝试获得相同的结果:

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))

它永远不会完成,进一步的调试显示 r 将始终分配给第一个值 x。看起来这两个实现应该是相同的?见Swapping variables

我也尝试过使用 var 而不是 let 但无济于事。我是否严重误解了解构赋值的意义或遗漏了一些微妙的东西?或者这是一个错误?

最佳答案

这不是解构赋值的问题,而是 ASI(自动分号插入)的问题。这两行:

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

在实践中是这样的:

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

这显然不是你的意思。要解决这个问题,请在 [:

前面添加一个分号

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))

当然,您可以在上一行的末尾添加缺少的分号(q = Math.floor(rdash/r);),但由于您通常不使用分号,我假设您使用的是 npm coding style .

关于javascript - ES6 函数中 while 循环中的解构赋值不会在循环外传播?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39747837/

相关文章:

javascript - 我可以使用解构来创建深层复制吗?

javascript - jQuery ui 可排序 : Toggle enable - disable sortable on the lists

javascript - 在 Android 的 WebView 中加载元素时隐藏该元素(或完全阻止其加载)

javascript - react Gatsby : adding css class dynamically not working in prod build

javascript - 增加JS数组中的Object键

javascript - 如何测试私有(private) React 组件

Javascript,在 React 应用程序中分配给函数组件中的 {},代码审查

javascript - WebGL。它是在 GPU 中创建缓冲区吗?

javascript - 使用尾随对象的键和递减键删除对象对象中的键

c# - C# 7 是否具有数组/可枚举解构?