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

如何用jQuery将数组中每两个元素相加以缩短数组长度?

使用jQuery实现数组两两元素求和缩短长度

给定原始数组:

const myList = [1.32412694112, 1.2904242732, 0.59030181, 0.5741011728, 0.6093767538, 0.5832783666, 0.5674657211999999, 0.5775693444];

期望得到的结果数组:

const resultList = [2.61455121432, 1.1644029828, 1.1926551204, 1.14503506559];

实现代码

利用jQuery的$.map()方法即可完成需求,核心逻辑是按顺序将数组中每两个元素分组求和:

const myList = [1.32412694112, 1.2904242732, 0.59030181, 0.5741011728, 0.6093767538, 0.5832783666, 0.5674657211999999, 0.5775693444];

const shortenedList = $.map(myList, function(item, index) {
  // 仅处理偶数索引的元素,与下一个元素求和后返回
  if (index % 2 === 0 && index + 1 < myList.length) {
    return item + myList[index + 1];
  }
});

console.log(shortenedList);
// 输出结果:[2.61455121432, 1.1644029828, 1.1926551204, 1.14503506559]

代码说明

  • $.map()会遍历原数组,根据回调函数的返回值生成新数组
  • 仅对偶数索引(0、2、4...)的元素进行处理,将其与下一个元素相加后作为新数组的元素;奇数索引的元素直接跳过,不加入结果
  • 额外判断index + 1 < myList.length是为了兼容数组长度为奇数的情况,避免出现越界错误

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

相关产品推荐
方舟 Agent Plan

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

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