javascript - 填充数组中未定义的元素
问题描述
我创建了一个空数组,例如长度为 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]
有任何想法吗?
解决方案
您可以使用它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);
推荐阅读
- ray - resnet示例的梯度同步问题
- javascript - 包含脚本
- python - CreateView 在提交时不保存,但在 UpdateView 上
- flutter - ScanStreamTransformer 上的 NULL 累加器
- javascript - JavaScript / Mocha - 如何测试是否等待函数调用
- java - 使用 with* 函数、TemporalAdjusters 或设置 TemporalFields 调整 ZonedDateTimes 之间有什么区别吗?
- php - 在 docker-compose 中使用 PhpStorm/Idea 和 Symfony 进行 Xdebug:仅在第一个文件 index_dev.php 处中断
- r - r 包文档中的方程式不起作用
- php - PHP 在 JS 中改变值
- php - 如何在 Google API PHP 客户端 2.2.2 版中设置 curl 超时