如何在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"
新数组中元素的问题索引已更改。
那我们怎样才能有效地解决这个问题呢?
答案 0 :(得分:2)
稀疏数组通常不是一个好主意,但是如果您具有 的功能,则可以使用Object.assign
:
let testArray = [];
testArray[4] = 'test4';
testArray[2] = 'test2';
testArray[15] = 'test15';
let otherTestArray = [];
otherTestArray[3] = 'test3';
otherTestArray[5] = 'test5';
const finalArr = Object.assign([], testArray, otherTestArray);
console.log(finalArr);
// (16) [empty × 2, "test2", "test3", "test4", "test5", empty × 9, "test15"]
答案 1 :(得分:2)
您可以将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; }
答案 2 :(得分:0)
您可以遍历每个忽略未定义的值,然后将该值分配给相同位置的另一个数组...
let testArray = [];
testArray[4] = 'test4';
testArray[2] = 'test2';
testArray[15] = 'test15';
//console.log(testArray);
let otherTestArray = [];
otherTestArray[3] = 'test3';
otherTestArray[5] = 'test5';
//console.log(otherTestArray);
let result = [];
for (var arr of [testArray, otherTestArray]){
console.log(arr.length);
for (var i = 0; i < arr.length; i++) {
if (arr[i] !== void(0)) // ignore undefined values
result[i] = arr[i];
}
}
console.log(result);