<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>纯函数&在树形结构查找第四遍</title> </head> <body> <script> // 纯函数 function getArea(r) { return Math.PI * r * r; } function memorize(func) { let obj = {}; return function () { let key = JSON.stringify([...arguments]); if (!obj[key]) { console.log(1); obj[key] = func(...arguments); } return obj[key]; }; } let a = memorize(getArea); console.log(a(2)); console.log(a(2)); console.log(a(2)); console.log(a(2)); console.log(a(2)); // 在树形结构中查找id let arr = [ { id: 1, children: [{ id: 2, children: [{ id: 6 }] }] }, { id: 3, children: [{ id: 4 }, { id: 5 }] } ]; function serachInTree(arr, id) { let result = null; if (!arr) { return; } for (let key in arr) { if (result !== null) { break; } if (arr[key].id === id) { result = arr[key]; break; } else if (arr[key].children && arr[key].children.length > 0) { result = serachInTree(arr[key].children, id); } } return result; } let b = serachInTree(arr, 2); console.log(b); </script> </body> </html>
树形结构中查找 id 出错,纯函数写对了