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

如何按指定索引将元素替换数组中的undefined占位值?

实现数组指定位置替换的方法

问题说明

现有三个数组:

  • positionsOfYears:存储需要替换元素的索引位置
  • emptyArray:包含10个undefined的占位数组
  • years:存储要插入到对应位置的年份值

原始代码如下:

const positionsOfYears = [2, 5, 8];
const emptyArray = [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined];
const years = [1992, 1999, 2000];

需要得到的输出数组:

[undefined, undefined, 1992, undefined, undefined, 1999, undefined, undefined, 2000, undefined]

实现方法

方法一:直接遍历赋值(最直观)

先复制原占位数组避免修改原数据,再遍历索引数组,将对应位置替换为目标年份:

const resultArray = [...emptyArray];
positionsOfYears.forEach((position, index) => {
  resultArray[position] = years[index];
});

方法二:使用Map配合map方法

先构建索引与年份的映射关系,再通过map方法批量替换:

const positionYearMap = new Map(
  positionsOfYears.map((pos, idx) => [pos, years[idx]])
);
const resultArray = emptyArray.map((val, idx) => positionYearMap.get(idx) ?? val);

方法三:使用splice方法(符合题目提到的splice)

如果必须使用splice,可以遍历每个索引位置,调用splice替换对应元素:

const resultArray = [...emptyArray];
positionsOfYears.forEach((position, index) => {
  // splice参数:目标索引、替换元素数量、新元素值
  resultArray.splice(position, 1, years[index]);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:25:27