两个数组结果用Java编写新数组

问题描述 投票:-1回答:3

用于获得动态数组的结果用于我的结果,完成了。现在我想要第一个数组的第一个值,第二个数组的第一个值...最后一个。

例如:

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

期待新的数组,如:

array3["test","test3","test1","test4","test2","test5"]
javascript php loops pdo
3个回答
1
投票

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

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);

0
投票

您可以转置数组并整理结果。

var array1 = ["test", "test1", "test2"],
    array2 = ["test3", "test4", "test5"],
    result = [array1, array2]
        .reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), [])
        .reduce((a, b) => a.concat(b));

console.log(result);

0
投票

我建议array.reduce()简洁实现。

array.reduce()
© www.soinside.com 2019 - 2024. All rights reserved.