将两个数组合并为一个 JS

Merging two arrays into one JS

我想创建一个函数,它接受两个不同的数组并对它们进行迭代,输出应该是一个一个一个地包含两个数组的新数组,如果它们的长度不同,则继续推入最长的数组的其余部分。我试过这个:

function mergeArrays(firstArray, secondArray) {
    let newArray = []
     firstArray.forEach((element, index) => {         
     newArray.push(element, secondArray[index])
});
    return newArray
}

如果我输入这个:

mergeArrays(["a", "b"], [1, 2, 3, 4])

输出应该是["a", 1, "b", 2, 3, 4],而不是在这种情况下当第一个数组的长度结束时停止,或者如果我在第一个和第二个数组之间切换作为参数,它会继续推动第一个但是在第二个它会推动 undefined。 我该如何解决?

也许试试这个

const newArray = [];
for (let index = 0; index < firstArray.length || index < secondArray.length, index++) {
  // find out if firstArray[index] exists
  // find out if secondArray[index] exists
  // add them to newArray
}