在Javascript中组合数组

时间:2016-04-18 20:07:39

标签: javascript arrays

如果我有多个阵列(我不知道它们的数量或长度)

arr1 = ["a","b","c"];
arr2 = ["red","green"];
arr3 = ["10","11","12","13"];

我想要像

这样的东西
res = [ 
          ["a","red","10"], ["a","red","11"],
          ["a","red","12"],["a","red","13"],
          ["a","green","10"],["a","green","11"], 
          ...   
     ]; 

你知道,结合它们......我不知道数组的数量或长度..最终结果是一个包含所有可能组合的数组。

1 个答案:

答案 0 :(得分:-2)

您应该能够使用数组方法reduce来创建单个数组。

/** @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Examples */

var arr1 = ["a", "b", "c"],
  arr2 = ["red", "green"],
  arr3 = ["10", "11", "12", "13"],
  flattened = [arr1, arr2, arr3].reduce(function(a, b) {
    return a.concat(b);
  }, []);

alert(flattened);