This article mainly introduces JS using closures to traverse the tree-like array of methods, the need for friends can refer to the following
When doing a company project, requires writing a method whose parameters are a menu array set and a menu ID, and the menu array is in the form of a tree json, as shown below: The code is as follows: [{"id":], "text": "Company Info", "Children": [ {"id": 1, "text": "Company Culture"}, {"id": 2, "text": "Recruitment Plan"}, & nbsp {"id": 6, "text": "Company News", "Children": [ {"id": $, "text": "Industry News"}]}, & nbsp {"id": One, "text": "Internal News", "Children": [ &N Bsp {"id": "Text": "Administrative Information"}, {"id": "," "Text": "High-level Instructions"}}, {"id": "Text": "Contact Us"}, {"id": num, "text": "Product Show", "Children": [ &N Bsp {"id": *, "text": "Power Products"}, &NBSP {"id":, "Text": "Accessories Introduction"}] }] Now give a menu ID of 32 to find the corresponding item and return the corresponding menu name, method is to iterate through the array, when the ID of the item is equal to the specified ID, the menu name is taken out, if not equal to see whether the current item has children, if the children is not empty and the number is greater than 0, then traversal children, then use the JavaScript closure, The traversal children method is placed in an anonymous method so that it is recursively recursive in the anonymous method, and when it encounters the ID of the same name, jumps out of the loop, and then returns the resulting menu name from the main method, the code reads as follows: The code is as follows: function Getmenuname ( menus, id { var name = ""; for (var i = 0; i < menus.length i++) { if (menus[i].id = ID) { name = Menu S[i].text; break; } else { (function () { var m = argumen Ts[0]; var menuid = arguments[1]; for (var j = 0; J < M.length J +) { if m[j].id = = Menu ID) { name = M[j].text; break; } &nbsP ELSE if m[j].children!= null && m[j].children.length > 0) { & nbsp Arguments.callee (M[j].children, Val);//Recursive anonymous method } } &N Bsp }) (Menus[i].children, id); } } return name; }