我在 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/