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

请教如何将数组num1=[1,2,4,3]转换为单个整数1243?

将数组形式的数字序列转换为单个整数的实现方法

以下是几种在JavaScript中实现数组转整数的常用方案:

1. 字符串拼接转换法

这是最直观的实现方式,通过数组拼接成字符串再转成整数:

const num1 = [1, 2, 4, 3];
// 方法1:使用parseInt
const num2 = parseInt(num1.join(''), 10);
// 方法2:使用Number构造函数
const num3 = Number(num1.join(''));

console.log(num2); // 输出 1243
console.log(num3); // 输出 1243

注意:parseInt的第二个参数10用于指定十进制解析,避免出现八进制等意外解析情况。

2. 数学累加计算法

如果不想依赖字符串转换,可以通过数学运算逐步构建整数,适合理解底层逻辑:

const num1 = [1, 2, 4, 3];
let num2 = 0;

for (const digit of num1) {
  num2 = num2 * 10 + digit;
}

console.log(num2); // 输出 1243

原理:每次将当前结果乘以10(相当于数字左移一位),再加上当前数组中的数字,逐步累加得到完整整数。

3. 大数场景处理(避免精度丢失)

如果数组长度过长(超过16位),普通Number类型会丢失精度,此时可以用BigInt类型处理:

const num1 = [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9];
// 字符串转BigInt
const num2 = BigInt(num1.join(''));
// 或者数学运算转BigInt
let num3 = 0n;
for (const digit of num1) {
  num3 = num3 * 10n + BigInt(digit);
}

console.log(num2); // 输出 99999999999999999n
console.log(num3); // 输出 99999999999999999n

内容的提问来源于stack exchange,提问作者Abrham Yeshitla

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 21:01:05