在JavaScript中合并两个具有交替值的数组

假设,我们需要编写一个函数,该函数接受两个数组并返回一个新数组,该数组包含从第一个数组到第二个数组的交替顺序的值。在这里,我们将循环遍历两个数组,同时从一个数组中选取另一个数组中的值,并将它们输入新数组中。

这样做的完整代码将是-

示例

const arr1 = [34, 21, 2, 56, 17];
const arr2 = [12, 86, 1, 54, 28];
let run = 0, first = 0, second = 0;
const newArr = [];
while(run < arr1.length + arr2.length){
   if(first > second){
      newArr[run] = arr2[second];
      second++;
   }else{
      newArr[run] = arr1[first];
      first++;
   }
   run++;
};
console.log(newArr);

输出结果

此代码的控制台输出将是-

[
   34, 12, 21, 86, 2,
   1, 56, 54, 17, 28
]