或者合并两个数组-JavaScript
我们需要编写一个JavaScript函数,该函数接受两个数组,并合并包含数组中元素的数组。
例如-
如果两个数组是-
const arr1 = [4, 3, 2, 5, 6, 8, 9]; const arr2 = [2, 1, 6, 8, 9, 4, 3];
那么输出应该是-
const output = [4, 2, 3, 1, 2, 6, 5, 8, 6, 9, 8, 4, 9, 3];
示例
以下是代码-
const arr1 = [4, 3, 2, 5, 6, 8, 9];
const arr2 = [2, 1, 6, 8, 9, 4, 3];
const mergeAlernatively = (arr1, arr2) => {
const res = [];
for(let i = 0; i < arr1.length + arr2.length; i++){
if(i % 2 === 0){
res.push(arr1[i/2]);
}else{
res.push(arr2[(i-1)/2]);
};
};
return res;
};
console.log(mergeAlernatively(arr1, arr2));输出结果
这将在控制台中产生以下输出-
[ 4, 2, 3, 1, 2, 6, 5, 8, 6, 9, 8, 4, 9, 3 ]