Home > front end >  Some doubt about recursive function return value
Some doubt about recursive function return value

Time:05-02

 
Var data=https://bbs.csdn.net/topics/[{
Id: 1,
Name: 'electronics'
Goods: [{
Id: 11,
Name: 'fridge,
Goods: [{
Id: 111,
Name: 'haier'
}]
}, {
Id: 12,
Name: 'air conditioner',
Goods: [{
Id: 121,
Name: 'gree'
}]
}]
}, {
Id: 2,
Name: 'food',
Goods: [{
Id: 21,
Name: 'chips'
}]
}]

//by using recursive forEach () times within the array of data
The function getID (product id) {
Var o={}
Product. The forEach (function (item) {
If (item id===id) {
O=item;
The console. The log (o)
} else if (item. Goods & amp; & Item. Goods. Length & gt; 0 {
GetID (item. Goods, id)
}
})
return o;
}

The console. The log (getID (data, 121))

The above code snippet, the first log normal output, but why the second log output is an empty object, is not normal for getID (item) goods, id) of the item after the recursive traversal to conform to the objects stored in the o the hollow object, how to print out a {}? (the output shown in the figure below)

CodePudding user response:

Because you're operating object o defined within the function, and then every time you getID will be reset to its {}

CodePudding user response:

Reset to zero after the assignment again, isn't it [align=center]
 
If (item id===id) {
O=item;
The console. The log (o)
} else if (item. Goods & amp; & Item. Goods. Length & gt; 0 {
GetID (item. Goods, id)

} [/align]

CodePudding user response:

reference 1/f, bubble fish _ response:
for you to operate object o defined within the function, and then reset to you every time when getID {}

I really want to know why the first layer has not been reset and the second will be reset?

CodePudding user response:

reference 1/f, bubble fish _ response:
for you to operate object o defined within the function, and then reset to you every time when getID {}

I probably understand, because circulation will go through it, every time go will go to the last object is the object name for the food, the food objects do not conform to the requirements of the lookup, did not perform the if and else if, but the recursive reset the object o,

CodePudding user response:

reference Aa raccoon dog, 4/f, grilled fish tofu cat replies:
Quote: reference 1/f, bubble fish _ response:
for you to operate object o defined within the function, and then reset to you every time when getID {}

I probably understand, because circulation will go through it, every time go will go to the last object is the object name for the food, the food objects do not conform to the requirements of the lookup, did not perform the if and else if, but the recursive reset the object o,


About the same, unless you're looking for is 1 and 2

And because Array. ForEach will traverse through all elements of the characteristics, it is not suitable for the recursive search, it will not immediately jump out after find the target, use the classical for loop to deal with
  • Related