You need to enable JavaScript to run this app. JavaScript中如何在数组每n个元素后插入指定元素且优化运行效率
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何在数组每n个元素后插入指定元素且优化运行效率

最优实现方案

要实现最低运行耗时,核心要避免频繁修改数组长度触发元素移位:如果用splice直接在原数组中间插入,每次插入都需要把插入位置后的所有元素后移一位,数组越大性能损耗越高,时间复杂度会达到O(n²)。
最优方案是预先计算新数组长度、一次性分配内存后按位置填充,时间复杂度为O(n),空间复杂度O(n),是当前场景下性能最高的实现。

function insertEveryTwo(originArr, insertElem) {
  const originLen = originArr.length;
  // 提前计算新数组长度:原长度 + 可插入次数(每2个原元素插1个,最后不足2个不补插)
  const newLen = originLen + Math.floor(originLen / 2);
  const result = new Array(newLen);
  let originIndex = 0;

  for (let i = 0; i < newLen;) {
    // 先填充2个原数组元素
    result[i++] = originArr[originIndex++];
    if (originIndex < originLen) {
      result[i++] = originArr[originIndex++];
      // 填完2个且还有剩余原元素时,插入指定元素
      if (originIndex < originLen) {
        result[i++] = insertElem;
      }
    }
  }
  return result;
}

// 测试用例
let arr = ["hello", "nice", "stack", "hi", "question", "random"];
console.log(insertEveryTwo(arr, "cat"));
// 输出:["hello", "nice", "cat", "stack", "hi", "cat", "question", "random"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 04:06:01