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

如何用for循环为嵌套数组新增差值计算列?

给嵌套数组新增差值列的实现方案

原始数组

var testArray = [
  ['Jan-2010', 867884],
  ['Feb-2010', 984655],
  ['Mar-2010', 322013],
  ['Apr-2010', -69417],
  ['May-2010', 310503],
  ['Jun-2010', 522857]
];

需求说明

通过for循环为每个内部数组新增索引为2的元素,该元素值为当前项的数值(索引1)与前一项数值的差值;第一项无前置项,差值直接取自身数值。

实现代码

// 遍历数组计算差值并添加新列
for (let i = 0; i < testArray.length; i++) {
  if (i === 0) {
    testArray[i].push(testArray[i][1]);
  } else {
    const diff = testArray[i][1] - testArray[i - 1][1];
    testArray[i].push(diff);
  }
}

// 查看结果(表格形式用console.table(testArray))
console.log(testArray);

执行结果

[
  ['Jan-2010', 867884, 867884],
  ['Feb-2010', 984655, 116771],
  ['Mar-2010', 322013, -662642],
  ['Apr-2010', -69417, -391430],
  ['May-2010', 310503, 379920],
  ['Jun-2010', 522857, 212354]
]

内容的提问来源于stack exchange,提问作者Jon Garnett-Smith

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 21:25:32