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

如何使用JavaScript Map方法合并数组中每隔n位的对应元素?

使用Map方法实现数组对应位置元素合并

你可以通过两种方式用map方法实现和原for循环相同的逻辑,以下是具体实现:

方法一:基于固定长度数组遍历索引

function test() {
  const array = [1, 2, 3, 4, 5, 6, 7, 8];
  const arrayNew = Array.from({ length: 4 }).map((_, index) => {
    return array[index] + array[index + 4];
  });
  console.log(arrayNew); // 输出 [6, 8, 10, 12]
}
  • Array.from({ length: 4 }) 创建一个长度为4的空数组,帮我们生成0到3的遍历索引,和原循环中n的取值范围一致。
  • map的第二个参数是当前遍历的索引,利用它直接匹配原数组中index和index+4位置的元素相加。

方法二:截取原数组前半部分后遍历

function test() {
  const array = [1, 2, 3, 4, 5, 6, 7, 8];
  const arrayNew = array.slice(0, 4).map((item, index) => {
    return item + array[index + 4];
  });
  console.log(arrayNew); // 输出 [6, 8, 10, 12]
}
  • slice(0,4)提取原数组前4个元素,遍历这些元素时,通过索引找到后半部分对应的元素完成相加,逻辑和原循环完全对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:05:24