JavaScript类型错误:无法混合BigInt与其他类型,求代码问题排查
解决BigInt混合类型操作错误并实现每一位存入数组
你的代码存在三个关键问题,直接导致了Type Error: Cannot mix BigInt and other types, use explicit conversions错误:
outputValue声明为const:你在循环中需要修改这个变量的值,但const声明的变量不可重新赋值,必须改为let。- 混合BigInt与Number类型运算:
- 比较
outputValue > 0里的0是Number类型,要改成BigInt类型的0n; - 取余操作
outputValue%10里的10是Number类型,要改成10n;
- 比较
- 用
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
相关产品推荐
相关产品推荐

