Simple: a function that calls itself internally is a recursive function
let num = 0;
function fu() {
console.log("Task print 5 sentences");
// Determine the condition
if (num == 5) {
// When the condition is complete,return exits the loop
return; } num++; Fu ()} FU () Note: There must be exit conditions (returnStack overflow error (stack overflow) is not reportedCopy the code
Requirement: Enter id to return the corresponding object data
// Define data
let data = [{
id: 1.name: "Home appliances".goods: [{
id: 11.gname: "Refrigerator".goods: [{
id: 111.gname: "Mobile phone"
}, {
id: 112.gname: "Electric fan"}]}, {id: 12.gname: "Washing machine"}]}, {id: 2.name: "Clothes"
}];
function fu(json, id) {
let obj = {} // The user returns object data
json.forEach(item= > {
//console.log(item); Prints two object data
// If the input id corresponds to item.id, the corresponding object is returned
if (item.id == id) {
obj = item;
return item
} else if (item.goods && item.goods.length > 0) {
// Select item.goods and item.goods.length > 0
// Call the function itself again, bypassing the traversalobj = fu(item.goods, id); }});return obj;
}
console.log(fu(data, 1));
console.log(fu(data, 2));
console.log(fu(data, 11));
console.log(fu(data, 12));
console.log(fu(data, 111));
Copy the code
Conclusion:
Advantages: Multiple layers of nested data can be found/returned
Disadvantages: prone to dead recursion “stack overflow error”, must have an exit condition (return exit loop)