This question already has answers here:
How to add two arrays in pairwise fashion

(3 个回答)


3年前关闭。




如何按此顺序合并或组合两个数组。
var list1 = ["A", "B", "C"];
var list2 = ["X", "Y", "Z"];

 var i = 0;
 for (i = 0; i < list1.length && list2.length; i++) {
     var list3[i] = list1[i] + list2[i];
 }

最后的结果应该是。
var list3 = ["AX", "BY", "CZ"];

最佳答案

您的代码工作正常,只需要在循环之前而不是在循环内部声明 list3

var list1 = ["A", "B", "C"];
var list2 = ["X", "Y", "Z"];

var i = 0;
var list3 = []; //observe this line here
for (i = 0; i < list1.length && list2.length; i++) {
     list3[i] = list1[i] + list2[i]; //var is removed
}

编辑

还要观察 for 循环条件 的变化
for (i = 0; i < list1.length && i < list2.length; i++) { // i needs to be less than list2.length as well
     list3[i] = list1[i] + list2[i]; //var is removed
}

注意
  • 上面的代码会保证list3的长度为Math.min (list1.length , list2.length)
  • 关于javascript - 如何在 Javascript 中合并/组合两个数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49451890/

    10-10 16:32