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 ] ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP