首页 > 解决方案 > 填充数组中未定义的元素

问题描述

我创建了一个空数组,例如长度为 9,其中:

const myArray = new Array(9)

我用动态索引中的 3 个值替换数组,但对于演示,让我们在索引 1、5 和 7 上说:即

myArray.splice(1, 1, 2)
myArray.splice(5, 1, 4)
myArray.splice(7, 1, 5)

我有另一个包含 6 个值的数组,我想一次填充 myArray 的未定义部分,即

const otherValues = [2,3,1,6,7,9]

有任何想法吗?

标签: javascriptarrays

解决方案


您可以使用它Array.from()来迭代所有数组值,同时还提供映射功能。映射函数可以取第一个值,otherValues或者如果它不是未定义的,它将使用当前元素。这将修改ohterValues,但是,如果需要,您可以在运行 Array.from 之前对其进行浅层克隆.slice()

请参见下面的示例:

const myArray = new Array(9)
const otherValues = [2,3,1,6,7,9];

myArray.splice(1, 1, 2);
myArray.splice(5, 1, 4);
myArray.splice(7, 1, 5);
const res = Array.from(myArray, x => x === undefined ? otherValues.shift() : x);

console.log(res);

如果您可以支持nullish coalescing operator ??,则可以将上述简化为:

const myArray = new Array(9)
const otherValues = [2,3,1,6,7,9];

myArray.splice(1, 1, 2);
myArray.splice(5, 1, 4);
myArray.splice(7, 1, 5);
const res = Array.from(myArray, x => x ?? otherValues.shift());

console.log(res);


推荐阅读