Javascript如何合并数组,使两个数组中的原始元素的索引保持不变
如何在JS中合并数组,使两个数组中的原始元素的索引保持不变 看来扩展阵列并不能满足我的需要:Javascript如何合并数组,使两个数组中的原始元素的索引保持不变,javascript,array-merge,Javascript,Array Merge,如何在JS中合并数组,使两个数组中的原始元素的索引保持不变 看来扩展阵列并不能满足我的需要: let testArray: Array<any> = []; testArray[4] = 'test4'; testArray[2] = 'test2'; testArray[15] = 'test15'; let otherTestArray = []; otherTestArray[3] = 'test3'; otherTestArray[5] = 'test5'; console
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: 设testArray=[]; testArray[4]=“test4”; testArray[2]=“test2”; testArray[15]=“test15”; 让otherTestArray=[]; otherTestArray[3]=“test3”; otherTestArray[5]=“test5”; const finalArr=Object.assign[],testArray,otherTestArray; console.logfinalArr;
//16[empty×2,test2,test3,test4,test5,empty×9,test15]稀疏数组通常是一个非常糟糕的主意,但如果必须这样做,可以使用Object.assign: 设testArray=[]; testArray[4]=“test4”; testArray[2]=“test2”; testArray[15]=“test15”; 让otherTestArray=[]; otherTestArray[3]=“test3”; otherTestArray[5]=“test5”; const finalArr=Object.assign[],testArray,otherTestArray; console.logfinalArr; //16[empty×2,test2,test3,test4,test5,empty×9,test15]您可以将和一个数组作为目标 设testArray=[]; testArray[4]=“test4”; testArray[2]=“test2”; testArray[15]=“test15”; 让otherTestArray=[]; otherTestArray[3]=“test3”; otherTestArray[5]=“test5”; console.logtestArray; 设testar=Object.assign[],testArray,otherTestArray; console.logtestar; .作为控制台包装{max height:100%!important;top:0;}您可以将和一个数组作为目标 设testArray=[]; testArray[4]=“test4”; testArray[2]=“test2”; testArray[15]=“test15”; 让otherTestArray=[]; otherTestArray[3]=“test3”; otherTestArray[5]=“test5”; console.logtestArray; 设testar=Object.assign[],testArray,otherTestArray; console.logtestar;
.作为控制台包装{max height:100%!important;top:0;}您可以忽略未定义的值对每个数组进行迭代,并将该值分配给同一位置的另一个数组 设testArray=[]; testArray[4]=“test4”; testArray[2]=“test2”; testArray[15]=“test15”; //console.logtestArray; 让otherTestArray=[]; otherTestArray[3]=“test3”; otherTestArray[5]=“test5”; //console.logotherTestArray; 让结果=[]; 对于[testArray,otherTestArray]的var arr{ console.logarr.length; 对于变量i=0;i