javascript - 两个数组结果在 Javascript 中创建新数组

标签 javascript loops

这是我的两个数据数组:

var array1 = ["test","test1","test2"];
var array2 = ["test3","test4","test5"];

我需要连接数组以获得以下结果:

array3["test","test3","test1","test4","test2","test5"]

如何存档?

最佳答案

考虑到,两个数组可以有不同数量的元素

var array1 = ["test","test1","test2"];
var array2 = ["test3","test4","test5"];
var maxLength = Math.max(array1.length, array2.length)
var array3 = [];
for (var index=0; index < maxLength; index++) {
    if (index < array1.length)
        array3.push(array1[index]);
    if (index < array2.length)
        array3.push(array2[index]);
}
console.log(array3);

关于javascript - 两个数组结果在 Javascript 中创建新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58388464/

相关文章:

javascript - 使用 lodash 过滤另一个数组的元素

java - 为什么我的 Java while 循环迭代了一半

php - 优化我的循环以返回而不是执行 10 次查询

Javascript SQL 请求 Bad Field Error in where 子句

javascript - Angular:从标签中应用 ngif

Javascript "If"语句或 "&&"逻辑运算符

python - 将 pandas df 中的行追加到新的 csv,同时保留标题一次?

python - 将数据帧python中每一行的前h值乘以k

c++ - 进度条功能不循环

javascript - 旧版浏览器中 classList `undefined` 的解决方法?