javaScript 遍历json 、递归调用 70
数据源:{"A":["a1","a2"],"B":["b1","b2"],"C":["c1","c2"]}要求结果:[{"A":"a1","B":"b1","C":"c1...
数据源:{"A":["a1","a2"],"B":["b1","b2"],"C":["c1","c2"]}
要求结果:
[{"A":"a1","B":"b1","C":"c1"},
{"A":"a1","B":"b1","C":"c2"},
{"A":"a1","B":"b2","C":"c1"},
{"A":"a1","B":"b2","C":"c2"},
{"A":"a2","B":"b1","C":"c1"},
{"A":"a2","B":"b1","C":"c2"},
{"A":"a2","B":"b2","C":"c1"},
{"A":"a2","B":"b2","C":"c2"}]
本人写的错误逻辑代码:
var list=[];
function fun(json,jsonItem){
for(var key in json){//for json
var array=json[key];//Array
jsonItem=jsonItem?jsonItem:{};
for(var i=0;i<array.length;i++){//for Array
var val=array[i];//new key value
var copyJson=$.extend({},json);//复制
delete copyJson[key];//删除当前的JSON对象
jsonItem[key]=val;
if($.isEmptyObject(json)){//如果为空{}
var copyJsonItem=$.extend({},jsonItem);//复制
list.push(copyJsonItem);
}else{
fun(copyJson);
}
}
}
}
调用 fun({"A":["a1","a2"],"B":["b1","b2"],"C":["c1","c2"]});
有一处复制错误 fun(copyJson); 应为 fun(copyJson,jsonItem); 展开
要求结果:
[{"A":"a1","B":"b1","C":"c1"},
{"A":"a1","B":"b1","C":"c2"},
{"A":"a1","B":"b2","C":"c1"},
{"A":"a1","B":"b2","C":"c2"},
{"A":"a2","B":"b1","C":"c1"},
{"A":"a2","B":"b1","C":"c2"},
{"A":"a2","B":"b2","C":"c1"},
{"A":"a2","B":"b2","C":"c2"}]
本人写的错误逻辑代码:
var list=[];
function fun(json,jsonItem){
for(var key in json){//for json
var array=json[key];//Array
jsonItem=jsonItem?jsonItem:{};
for(var i=0;i<array.length;i++){//for Array
var val=array[i];//new key value
var copyJson=$.extend({},json);//复制
delete copyJson[key];//删除当前的JSON对象
jsonItem[key]=val;
if($.isEmptyObject(json)){//如果为空{}
var copyJsonItem=$.extend({},jsonItem);//复制
list.push(copyJsonItem);
}else{
fun(copyJson);
}
}
}
}
调用 fun({"A":["a1","a2"],"B":["b1","b2"],"C":["c1","c2"]});
有一处复制错误 fun(copyJson); 应为 fun(copyJson,jsonItem); 展开
1个回答
2013-01-21
展开全部
用排列算法,网上可以搜到
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询