Javascript ES6 - 映射多个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32937181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:24:10  来源:igfitidea点击:

Javascript ES6 - map multiple arrays

javascriptecmascript-6

提问by nha

Is there a feature in JavaScript 6 that allows to map over multiple arrays ?

JavaScript 6 中是否有允许映射多个数组的功能?

Something like a zipper :

类似于拉链的东西:

 var myFn = function (a, b) { console.log(a, b);}
  var arr1 = ['a', 'b', 'c'];
  var arr2 = [1, 2, 3];

  arr1.map(myFn, arr2); // imaginary syntax.
  // prints :
  // a 1
  // b 2
  // c 3

采纳答案by lukewestby

Unfortunately, no. What you are looking for is commonly called zipor zipWith. See lodash's implementation for a reference: https://lodash.com/docs#zipWith

抱歉不行。您要查找的内容通常称为zipzipWith。参考 lodash 的实现:https://lodash.com/docs#zipWith

回答by Benjamin Gruenbaum

As the other answer points out, this is commonly known as a zip. It can be implemented as:

正如另一个答案所指出的,这通常称为zip. 它可以实现为:

let zipped = arr1.map((x, i) => [x, arr2[i]]);

Or as a function, basically:

或者作为一个函数,基本上:

let zip = (a1, a2) => a1.map((x, i) => [x, a2[i]]); 

Which would let you do:

这会让你做:

zip(["a","b","c"], [1,2,3]); // ["a", 1], ["b", 2], ["c", 3]

回答by Onaracs

You could also use reduceto get the desired outcome:

您还可以使用reduce来获得所需的结果:

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

arr1.reduce((acc, current, index) => {
   console.log(current, arr2[index])
   return [...acc, current, arr2[index]]
}, [])

// a 1
// b 2
// c 3
// returns ["a", 1, "b", 2, "c", 3]