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

JavaScript类型错误:无法混合BigInt与其他类型,求代码问题排查

解决BigInt混合类型操作错误并实现每一位存入数组

你的代码存在三个关键问题,直接导致了Type Error: Cannot mix BigInt and other types, use explicit conversions错误:

  1. outputValue声明为const:你在循环中需要修改这个变量的值,但const声明的变量不可重新赋值,必须改为let。
  2. 混合BigInt与Number类型运算:
    • 比较outputValue > 0里的0是Number类型,要改成BigInt类型的0n;
    • 取余操作outputValue%10里的10是Number类型,要改成10n;
  3. 用Math.floor处理BigInt:Math.floor仅支持Number类型,无法直接处理BigInt。由于每次循环中outputValue都是10的倍数(取余后剩余的数),直接用BigInt除法outputValue / 10n就能得到整数结果,不需要Math.floor。

另外,原代码存入数组的顺序是从个位到最高位,最后需要反转数组才能得到正确的高位到低位顺序。

修正后的代码:

var plusOne = function(digits) {
    let outputValue = BigInt(digits.join("")) + 1n;
    let arr = [];
    while(outputValue > 0n)
    {
        arr.push(outputValue % 10n);
        outputValue = outputValue / 10n;
    }
    return arr.reverse();
};

console.log(plusOne([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3])); 

内容的提问来源于stack exchange,提问作者Aravind Raghunath

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 12:55:10