<!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> // 树形图查找 let arr = [ { id: 1, name: '1', children: [ { id: 11, name: '11', children: [ { id: 111, name: '111' } ] } ] }, { id: 2, name: '2', children: [ { id: 22, name: '22', children: [ { id: 222, name: '222' } ] } ] } ]; function searchInTree(arr, id) { let result = null; if (!arr) { return null; } 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 = searchInTree(arr[key].children, id); } } return result; } // 第二遍传参数的时候只传了一个参数 console.log(searchInTree(arr, 2)); 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(111); obj[key] = func(...arguments); } return obj[key]; }; } let a = memorize(getArea); console.log(a(5)); console.log(a(5)); console.log(a(5)); console.log(a(5)); console.log(a(5)); console.log(a(6)); </script> </body> </html>