在 JavaScript 中合并两个数组

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/7 3:56:17

我们需要编写一个 JavaScript 函数,该函数接受两个长度相同的数组。

然后,我们的函数应该合并数组的相应元素,以形成输出数组的相应子数组,最后返回输出数组。

如果两个数组 −

const arr1 = ['a', 'b', 'c'];
const arr2 = [1, 2, 3];

那么输出应该是 −

const output = [
   ['a', 1],
   ['b', 2],
   ['c', 3]
];

示例

其代码为 −

const arr1 = ['a', 'b', 'c'];
const arr2 = [1, 2, 3];
const combineCorresponding = (arr1 = [], arr2 = []) => {
   const res = [];
   for(let i = 0; i < arr1.length; i++){
      const el1 = arr1[i];
      const el2 = arr2[i];
      res.push([el1, el2]);
   };
   return res;
};
console.log(combineCorresponding(arr1, arr2));

输出

控制台中的输出将是 −

[ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]

相关文章


有用资源