JavaScript 代码优化:使用 localStorage 存储和更新关键词过滤数据
The code can be optimized by removing unnecessary code and simplifying the logic. Here is the optimized code:\n\njavascript\nlet KeywordFiltering = [\n { name: \"名字\", class: \"username\", data: [4, 5, 6] },\n { name: \"文案\", class: \"Copywriting\", data: [1, 2, 3] },\n { name: \"全选\", class: \"selectall\", data: [] }\n]\n\nlet Filtering = [\n { name: \"名字\", class: \"username\", data: [] },\n { name: \"文案\", class: \"Copywriting\", data: [] },\n { name: \"标签\", class: \"Tag\", data: [] },\n { name: \"全选\", class: \"selectall\", data: [] }\n]\n\nif (!localStorage.getItem(\"KeywordData\")) {\n localStorage.setItem(\"KeywordData\", JSON.stringify(KeywordFiltering))\n} else {\n let i = JSON.parse(localStorage.getItem(\"KeywordData\"))\n i = i.filter(item => item.data.length != 0)\n i.forEach(item => {\n let subItem = Filtering.find(sub => sub.name === item.name)\n if (subItem) {\n Object.assign(subItem, item)\n }\n })\n console.log(Filtering);\n}\n\n\nIn the optimized code:\n1. The unnecessary console.log statements are removed.\n2. The map function is replaced with forEach to modify the Filtering array in place.\n3. The find function is used to find the matching subItem in the Filtering array based on the name property.\n4. The Object.assign function is used to copy the properties from item to subItem.
原文地址: http://www.cveoy.top/t/topic/p56Z 著作权归作者所有。请勿转载和采集!