You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

添加console.log后GCD函数报错,移除则正常的原因排查

代码添加console.log后报错的原因分析

原代码

function gcd(a, b) {
    while (b !== 0) {
        console.log(a,b)
        [a, b] = [b, a % b];
    }
    return a;
}

console.log(gcd(4,96))

报错信息

TypeError: Cannot set properties of undefined (setting '96')
at gcd (C:\Users\Rajashekar\example.js:332:16)
at Object. (C:\Users\Rajashekar\example.js:337:13)
at Module._compile (node:internal/modules/cjs/loader:1241:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1295:10)
at Module.load (node:internal/modules/cjs/loader:1091:32)
at Module._load (node:internal/modules/cjs/loader:938:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
at node:internal/main/run_main_module:23:47

原因解析

这是JavaScript**自动分号插入(ASI)**机制导致的语法解析错误:

  • console.log(a,b)末尾没有加分号,JavaScript没有在这里自动补充分号,而是把它和下一行的数组解构语句合并成了同一条代码:
    console.log(a,b)[a, b] = [b, a % b];
    
  • console.log的返回值是undefined,代码试图给undefined的某个属性赋值,自然会抛出“无法给undefined设置属性”的错误。

解决方法

两种方式任选其一:

  1. 在console.log语句末尾添加分号:
    console.log(a,b);
    [a, b] = [b, a % b];
    
  2. 在数组解构语句的行首添加分号:
    console.log(a,b)
    ;[a, b] = [b, a % b];
    

内容的提问来源于stack exchange,提问作者Rajashekar Reddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 20:12:06