JavaScript 等同于 Python 的 zip 函数

javascriptobject oriented programmingweb development

我们必须编写 JavaScript 等同于 Python 的 zip 函数的函数。也就是说,给定多个长度相等的数组,我们需要创建一个成对的数组。

例如,如果我有三个看起来像这样的数组 −

const array1 = [1, 2, 3];
const array2 = ['a','b','c'];
const array3 = [4, 5, 6];

输出数组应为 −

const output = [[1,'a',4], [2,'b',5], [3,'c',6]]

因此,让我们为这个函数 zip() 编写代码。我们可以通过多种方式来实现这一点,例如使用 reduce() 方法或 map() 方法,或者使用简单的嵌套 for 循环,但在这里我们将使用嵌套 forEach() 循环来实现。

示例

const array1 = [1, 2, 3];
const array2 = ['a','b','c'];
const array3 = [4, 5, 6];
const zip = (...arr) => {
   const zipped = [];
   arr.forEach((element, ind) => {
      element.forEach((el, index) => {
         if(!zipped[index]){
            zipped[index] = [];
         };
         if(!zipped[index][ind]){
            zipped[index][ind] = [];
         }
         zipped[index][ind] = el || '';
      })
   });
   return zipped;
};
console.log(zip(array1, array2, array3));

输出

控制台中的输出将是 −

[ [ 1, 'a', 4 ], [ 2, 'b', 5 ], [ 3, 'c', 6 ] ]

相关文章