以下转载了来自 segmentfault的一个回答

  1. 第一种
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<script type="text/javascript">
        var data = new Array(new Array(1, 2, 3), new Array(4, 5, 6));
        var result = [];
        console.log(data);
        function descartes(arrIndex, aresult){
            if (arrIndex >= data.length) {
                result.push(aresult);
                return ;
            }
            var aArr = data[arrIndex];
            for (var i = 0; i < aArr.length; ++i) {
                var theResult = aresult.slice(0, aresult.length);
                theResult.push(aArr[i]);
                descartes(arrIndex + 1, theResult);
            }
        }
        descartes(0, []);
        console.log(result);
    </script>
  1. 第二种
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function descartes(){
    if( arguments.length < 2 ) return arguments[0] || [];

    return [].reduce.call(arguments, function(col, set) {
        var res = [];
        col.forEach(function(c) {set.forEach(function(s) {
            var t = [].concat( Array.isArray(c) ? c : [c] );
            t.push(s);
            res.push(t);
        })});
        return res;
    });
}
descartes([1,2,3],[4,5,6],[7,8,9],[10,11,12]);