如何在JavaScript中将两个数组合并为多行数组?
在JavaScript中合并两个数组为对应元素组成的二维数组
给定两个数组:
const array1 = [1, 2, 3]; const array2 = ['one', 'two', 'three'];
需要得到结果:
const res = [[1,'one'],[2,'two'],[3,'three']];
下面是两种适合JavaScript初学者的实现方法:
方法一:使用Array.map()(简洁写法)
map方法可以遍历数组的每个元素,同时获取元素的索引,利用索引匹配另一个数组的对应元素:
const array1 = [1, 2, 3]; const array2 = ['one', 'two', 'three']; const res = array1.map((item, index) => [item, array2[index]]); console.log(res); // 输出 [[1,'one'],[2,'two'],[3,'three']]
说明:map会返回一个新数组,每个元素是回调函数返回的[item, array2[index]],也就是两个数组对应位置的元素组成的子数组。
方法二:使用for循环(基础逻辑写法)
如果想更直观理解数组遍历的过程,可以用普通for循环:
const array1 = [1, 2, 3]; const array2 = ['one', 'two', 'three']; const res = []; // 遍历数组索引,将对应元素组合后推入结果数组 for (let i = 0; i < array1.length; i++) { res.push([array1[i], array2[i]]); } console.log(res); // 输出目标结果
补充:如果不确定两个数组长度是否一致,可以取两者的最小长度来避免出现undefined:
const minLength = Math.min(array1.length, array2.length); const res = []; for (let i = 0; i < minLength; i++) { res.push([array1[i], array2[i]]); }
内容的提问来源于stack exchange,提问作者Moataz Imad
相关产品推荐
相关产品推荐

