3 回答
TA贡献1784条经验 获得超2个赞
尝试以下代码
function cross(inputs){
let result = inputs[0].map(item => [item]);
for(let cross_item of inputs.slice(1)){
result = cross_item.reduce((acc,target)=>(result.forEach(result_item=>acc.push([...result_item,target])),acc),[]);
}
return result;
}
console.log(cross([['n','o','t'], ['i', 'n'], ['a'],['(',')']]));
----------------其实可以再短一点------------------
function cross(inputs){
return inputs.reduce((result,cross_item)=> cross_item.reduce((acc, target) => (result.forEach(result_item => acc.push([...result_item, target])), acc), []))
}
TA贡献2039条经验 获得超7个赞
放进二维数组里 递归组合
let arr=[
[11,12],
[21,22,23],
[31],
[41,42]
]
f(arr,0,[])
function f(arr,k,temp){
if(k==arr.length){
console.log(JSON.stringify(temp))
return
}
for(let i=0;i<arr[k].length;i++){
temp[k]=arr[k][i]
f(arr,k+1,temp)
}
}
添加回答
举报