1. 程式人生 > >js 數組全排列組合算法

js 數組全排列組合算法

每次 下標 style ack 外部 避免 都是 post 直接

function doCombination(arr) {
    var count = arr.length - 1; //數組長度(從0開始)
    var tmp = [];
    var totalArr = [];// 總數組

    return doCombinationCallback(arr, 0);//從第一個開始
    //js 沒有靜態數據,為了避免和外部數據混淆,需要使用閉包的形式
    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; } } //測試數組 var arr = [ [1,2,3,4,5], [a,b,c,d], [成功, 失敗] ]; //調用方法 document.write(doCombination(arr));

js 數組全排列組合算法