This question already has answers here:
Merge multiple arrays based on their index using javascript
                                
                                    (7个答案)
                                
                        
                3个月前关闭。
            
        

我试图结合两个数组的数组元素来创建一个新的合并元素数组。
这是我在做什么。

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];

var arr = [];

for(let i=0; i< array1.length;i++){
    for(let j=0; j < array2.length;j++){
        arr.push(array1[i]+array2[j])
    }
}


这是我得到的结果。

["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]


但是预期的结果是

['ad','be','cf']


我该如何实现?我应该在哪里使用break语句?

最佳答案

不要使用嵌套循环-而是在其中一个数组上使用.map,在另一个数组中访问相同的索引并进行连接:



const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];

const combined = array1.map((char, i) => char + array2[i]);
console.log(combined);

10-05 20:40
查看更多