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

JavaScript中如何截断二维数组内的浮点数取整数部分?

二维数组浮点数截断为整数的实现方法

要把二维数组中所有浮点数截断为整数(如23.123→23),核心是遍历数组的每一层元素,对每个数值应用截断方法。你之前用Math.trunc或_.toInteger没得到预期结果,大概率是没处理好二维数组的嵌套遍历。

以下是几种可行实现:

原生JavaScript方法(用Math.trunc)

利用Array.map()嵌套遍历,外层处理子数组,内层处理每个数值:

const arr = [
  [1.05, 2.0123, 3.123, 4.123],
  [1.05, 2.0123, 3.123, 4.123], 
  [1.05, 2.0123, 3.123, 4.123]
];

const output = arr.map(subArr => subArr.map(num => Math.trunc(num)));
console.log(output);
// 输出:[[1,2,3,4],[1,2,3,4],[1,2,3,4]]

Math.trunc()会直接去除数值的小数部分,完全符合你的截断需求。

Lodash方法(用_.toInteger)

同样需要嵌套遍历数组,结合lodash的_.map和_.toInteger:

const _ = require('lodash');

const arr = [
  [1.05, 2.0123, 3.123, 4.123],
  [1.05, 2.0123, 3.123, 4.123], 
  [1.05, 2.0123, 3.123, 4.123]
];

const output = _.map(arr, subArr => _.map(subArr, _.toInteger));
console.log(output);
// 输出:[[1,2,3,4],[1,2,3,4],[1,2,3,4]]

补充:用parseInt实现

如果场景中都是纯数字,也可以用parseInt(注意要指定基数10):

const output = arr.map(subArr => subArr.map(num => parseInt(num, 10)));

常见错误原因

如果你之前尝试后失败,可能是只处理了外层数组,比如直接写arr.map(Math.trunc)——这样会把整个子数组传给Math.trunc,数组不是数值类型,最终得到的是NaN数组,必须嵌套遍历每一层元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 15:50:38