js/ts 中把一个数组集合的前x位放到另一个数组集合的n位中。请问有什么更简洁的方案吗

//{"name":0}
let ArraryOne = [ ];
for(let i = 0; i < 10; i++){
ArraryOne.push({"_name":i});
}
let ArraryTwo= [ ]
let tIndex = 0;
//这个是我现有的,感觉不太对。如果用到One数组的前100位放到Two数组中,这种就很不对
//(不考虑具体需求)
for (let tL = 0; tL < tLength; tL++) {
let tArrary: any[] = []
for (let index = tIndex; index < ArraryOne.length; index += 3) {
if (ArraryOne[index] != null) {
tArrary.push(ArraryOne[index]);
if (this.ArraryOne[index + 1] != null) {
tArrary.push(this.ArraryOne[index + 1]);
if (this.ArraryOne[index + 2] != null) {
tArrary.push(this.ArraryOne[index + 2]);
}
}
}
if (Array.isArray(tArrary)) {
ArraryTwo[tL] = tArrary;
tIndex = index += 3;
break;
}
}
}

回答

//前n,插入位置m
var n = 3,m = 2;
var a = ["a1", "a2", "a3", "a4", "a5"];
var b = ["b1", "b2", "b3", "b4", "b5"];
//场景一、将前n作为数组插入集合位置m
//b.splice(m, 0, a.slice(0, n));
//console.log(b) //['b1', 'b2', Array(3), 'b3', 'b4', 'b5']
//场景二、将前n逐个插入位置m,并依次往后继续插入,使之成为一个同类型数组
a.slice(0, n).forEach((item, i) => {
b.splice(m + i, 0, item);
})
console.log(b) // ['b1', 'b2', 'a1', 'a2', 'a3', 'b3', 'b4', 'b5']

//以上,希望可以帮助到你。

以上是js/ts 中把一个数组集合的前x位放到另一个数组集合的n位中。请问有什么更简洁的方案吗的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>