JS:数组排列组合
-
原数组
const source = [ ['black', 'white', 'red', 'blue'], ['128GB', '256GB', '512GB'], ['zhengzhou', 'shenzhen', 'vietnam'], ]
-
方法
let temp = [] let results = [] function combine(arr, index = 0) { arr[index].forEach(item => { temp[index] = item index + 1 < arr.length ? combine(arr, index + 1) : results.push(temp.slice()) }) }
-
执行
combine(source) console.log(results)
-
输出
[ [ 'black', '128GB', 'zhengzhou' ], [ 'black', '128GB', 'shenzhen' ], [ 'black', '128GB', 'vietnam' ], [ 'black', '256GB', 'zhengzhou' ], [ 'black', '256GB', 'shenzhen' ], [ 'black', '256GB', 'vietnam' ], [ 'black', '512GB', 'zhengzhou' ], [ 'black', '512GB', 'shenzhen' ], [ 'black', '512GB', 'vietnam' ], [ 'white', '128GB', 'zhengzhou' ], [ 'white', '128GB', 'shenzhen' ], [ 'white', '128GB', 'vietnam' ], [ 'white', '256GB', 'zhengzhou' ], [ 'white', '256GB', 'shenzhen' ], [ 'white', '256GB', 'vietnam' ], [ 'white', '512GB', 'zhengzhou' ], [ 'white', '512GB', 'shenzhen' ], [ 'white', '512GB', 'vietnam' ], [ 'red', '128GB', 'zhengzhou' ], [ 'red', '128GB', 'shenzhen' ], [ 'red', '128GB', 'vietnam' ], [ 'red', '256GB', 'zhengzhou' ], [ 'red', '256GB', 'shenzhen' ], [ 'red', '256GB', 'vietnam' ], [ 'red', '512GB', 'zhengzhou' ], [ 'red', '512GB', 'vietnam' ], [ 'blue', '128GB', 'zhengzhou' ], [ 'blue', '128GB', 'shenzhen' ], [ 'blue', '128GB', 'vietnam' ], [ 'blue', '256GB', 'zhengzhou' ], [ 'blue', '256GB', 'shenzhen' ], [ 'blue', '256GB', 'vietnam' ], [ 'blue', '512GB', 'zhengzhou' ], [ 'blue', '512GB', 'shenzhen' ], [ 'blue', '512GB', 'vietnam' ] ]
网友评论