使用闭包处理数组矩阵组合(如:3*5*3)
function doCombination(arr) { const count = arr.length - 1; //数组长度(从0开始) let [tmp, totalArr] = [[], []]; return doCombinationCallback(arr, 0); // 从第一个开始 // 为了避免和外部数据混淆,需要使用闭包的形式 function doCombinationCallback(arr, curr_index) { for (val of arr[curr_index]) { tmp[curr_index] = val; // 以curr_index为索引,加入数组 // 当前循环下标小于数组总长度,则需要继续调用方法 if (curr_index < count) { doCombinationCallback(arr, curr_index + 1); // 继续调用 } else { totalArr.push(tmp); // (直接给push进去,push进去的不是值,而是值的地址) } // js 对象都是 地址引用(引用关系),每次都需要重新初始化,否则 totalArr的数据都会是最后一次的 tmp 数据; oldTmp = tmp; tmp = []; for (index of oldTmp) { tmp.push(index); } } return totalArr; } } // 测试数组 let arr = [ ['350ml', '500ml', '750ml'], ['2016', '2017', '2018', '2019', '2020'], ['43°', '53°', '57°'] ]; // 调用方法 console.log(doCombination(arr));
结果如下:
希望大佬看到有不对的地方,提出博主予以改正!