大佬们遇到过这个问题吗?JavaScript求一返回方法

functionreturnIt(code){
//returnobj
}
通过已知value(编码)返回对象e.g.returnIt('000003');返回{value:'000003',label:'渭南市',isLeaf:true}
constcityList=[
{
label:'全国',
value:'000000',
children:[
{
label:'陕西省',
value:'000001',
children:[
{value:'000002',label:'西安市',isLeaf:true},
{value:'000003',label:'渭南市',isLeaf:true},
],
},
{label:'上海',value:'000005',isLeaf:true},
{label:'北京',value:'000006',isLeaf:true},
{
label:'河南省',
value:'000007',
children:[
{value:'000008',label:'信阳',isLeaf:true},
{value:'000009',label:'周口',isLeaf:true},
{value:'000010',label:'其他',isLeaf:true},
],
},
{
label:'山东省',
value:'000011',
children:[
{value:'000012',label:'枣庄',isLeaf:true},
{value:'000013',label:'烟台',isLeaf:true},
{value:'000014',label:'淄博',isLeaf:true},
],
},
]
}];
哔哔one
浏览 271回答 2
2回答

白板的微信

简单递归一下就行了functionreturnIt(code,list){for(letitemoflist){if(item.value===code)returnitem;if(item.children){constchild=returnIt(code,item.children);if(child)returnchild;}}}因为是纯函数,调用需把cityList作为参数传递进去constresult=returnIt('000003',cityList);console.log(result);

呼如林

functiongetReturnIt(arr,value){letnewarr=arr;letcurr=null;while(newarr.length>0){curr=newarr.shift();if(value===curr.value){returncurr}if(curr.children){newarr.push(...curr.children)}}}console.log(getReturnIt(cityList,'000008'))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript