如何在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; }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)