【发布时间】:2017-02-06 10:52:57
【问题描述】:
我在 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 无济于事。我是否严重误解了解构分配的意义或遗漏了一些微妙的东西?还是bug?
【问题讨论】:
-
您的
q和temp变量是 implicitly global。使用严格模式! -
顺便说一句,你为什么不直接写
function gcd(r, rdash) {并省略let [r, rdash] = [x, y]?
标签: javascript ecmascript-6 destructuring