如何按指定索引将元素替换数组中的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
相关产品推荐
相关产品推荐

