原文博客地址
现在有一批手机,其中颜色有[‘白色’,‘黑色’,‘金色’,‘粉红色’];内存大小有[‘16G’,‘32G’,‘64G’,‘128G’],版本有[‘移动’,‘联通’,‘电信’],要求写一个算法,实现[[‘白色’,‘16G’,‘移动’], [‘白色’,‘16G’,‘联通’] …]这样的组合,一个数组里面包含若干个数组,进行组合。
<script>
function doExchange(arr, depth)
{
for (var i = 0; i < arr[depth].length; i++) {
result[depth] = arr[depth][i]
if (depth != arr.length - 1) {
doExchange(arr, depth + 1)
} else {
results.push(result.join('-'))
}
}
}
function test(arr)
{
results = [];
result = [];
doExchange(arr, 0);
console.log(results.length, results.join(','));
}
garr = [
['红色', '绿色', '白色'],
['大', '中', '小'],
['64G', '128G'],
]
test(garr)
打印结果