首页 > 解决方案 > 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"

新数组中元素的问题索引已更改。

那么我们如何才能有效地解决这个问题呢?

标签: javascriptarray-merge

解决方案


您可以将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; }


推荐阅读