JavaScript代码实现
/**
* 组合多个数组
* @param {...Array} arrays
* @returns
*/
function combine(...arrays) {
let list = [];
let helper = function (index, prev) {
// 当前数组
let array = arrays[index];
// 是否为最后一个数组
let is_last = arrays.length - 1 == index;
for (let item of array) {
let current = prev.concat(item);
if (is_last) {
list.push(current);
} else {
helper(index + 1, current);
}
}
};
helper(0, []);
return list;
}
let names = ['iPhone X', 'iPhone XS'];
let colors = ['黑色', '白色'];
let storages = ['64g', '256g'];
console.log(combine(names, colors, storages));
输出
[
[ 'iPhone X', '黑色', '64g' ],
[ 'iPhone X', '黑色', '256g' ],
[ 'iPhone X', '白色', '64g' ],
[ 'iPhone X', '白色', '256g' ],
[ 'iPhone XS', '黑色', '64g' ],
[ 'iPhone XS', '黑色', '256g' ],
[ 'iPhone XS', '白色', '64g' ],
[ 'iPhone XS', '白色', '256g' ]
]
PHP实现版
关注
打赏