题目描述有一个树形结构:vardata={key1:'str1',key2:{key3:'str3',key4:'str4',key5:{key6:'str6'},key8:{key9:'str9'}},key7:"str7"//...}实现一个方法getKeys(data,str),获取字符串str在data中所有的上级节点名称,例如:getKeys(data,'str1')返回'key1'getKeys(data,'str3')返回'key2key3'getKeys(data,'str6')返回'key2key5key6'
2 回答
万千封印
TA贡献1891条经验 获得超3个赞
functiongetKeys(data,str){varresult=[];functionrecursion(data,str){for(varkeyindata){if(data[key]==str){result.push(key);returnresult;}if(typeofdata[key]=='object'){result.push(key);returnrecursion(data[key],str)}}}recursion(data,str);returnresult.join('');}
HUH函数
TA贡献1836条经验 获得超4个赞
varresult=[]constGetKey=(data,key)=>{for(letvindata){if(data[v]==key){result.push(v)returnresult}if(typeofdata[v]=='object'){result.push(v)returnGetKey(data[v],key)}}}
添加回答
举报
0/150
提交
取消