& lt; script>
Var data=https://bbs.csdn.net/topics/[{
Id: 1,
Name: 'home appliances'
Goods: [{
Id: 11,
Gname: 'fridge,
Goods: [{
Id: 111,
Gname: 'haier'
}, {
Id: 112,
Gname: 'beauty'
},]
}, {
Id: 12,
Gname: 'washing machine'
}]
}, {
Id: 2,
Name: 'clothing'
}];
//we want to do the input id number, you can return the data object
//1. Use a forEach to traverse the inside of each object
The function getID (json, id) {
Var o={}
{json. ForEach (function (a)
If (Anderson, d==id) {
console.log(a);
O=a;
}
Else if (al-qeada oods& & Atul gawande oods. Length> 0 {
GetID (al-qeada oods, id)
}
})
return o;
}
//the console. The log (getID (data, 1));
The console. The log (getID (data, 11));
//getID (data, 11);
</script>
Why the last o object is not assignment in it?
CodePudding user response:
Because you are second in the recursive call getID (al-qeada oods, id) the return value of not receiving and return to a layer,Returns the result in the recursive to one layer up back to the original call,
CodePudding user response:
Else if, to o=getID (al-qeada oods, id)//the return value is assigned to the recursion o, finally return to o