相当于Python的zip函数的JavaScript
我们必须编写Python的zip函数的JavaScript等效函数。也就是说,给定多个相等长度的数组,我们需要创建一个成对的数组。
例如,如果我有三个看起来像这样的数组-
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 ] ]
热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短