javascript - Javascript如何合并数组以使两个数组中原始元素的索引保持不变
问题描述
如何在 JS 中合并数组,使两个数组中原始元素的索引保持不变?
似乎扩展数组没有做我需要的事情:
let testArray: Array<any> = [];
testArray[4] = 'test4';
testArray[2] = 'test2';
testArray[15] = 'test15';
let otherTestArray = [];
otherTestArray[3] = 'test3';
otherTestArray[5] = 'test5';
console.log(testArray);
let testar = [...testArray, ...otherTestArray];
console.log(testar);
2:"test2"
4:"test4"
15:"test15"
19:"test3"
21:"test5"
新数组中元素的问题索引已更改。
那么我们如何才能有效地解决这个问题呢?
解决方案
您可以将Object.assign
数组作为目标。
let testArray = [];
testArray[4] = 'test4';
testArray[2] = 'test2';
testArray[15] = 'test15';
let otherTestArray = [];
otherTestArray[3] = 'test3';
otherTestArray[5] = 'test5';
console.log(testArray);
let testar = Object.assign([], testArray, otherTestArray);
console.log(testar);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- c++ - 这段代码在做什么,我该如何操作它?
- python-3.x - 处理要根据测试用例的通过或失败触发操作的 pytest 用例
- html - 图片的高度:Chrome 中为 0,但 Firefox 中没有
- python - kivy - 一键更改两次
- arrays - 在单个循环中更新多个累加器时遇到问题
- php - 如何组合具有两个 user_id 的表并在视图中显示
- matlab - 使用带有可选输入参数的函数
- .net-core - 使用 linux 域套接字在 .NET Core 和 C 之间进行 Thrift 通信
- java - 主线程在等待(5 秒)中不等待其他线程;
- scope - Julia 变量范围