// 获取当前日期 const today = new Date().toDateString();

// 获取当前页面使用次数 let count = parseInt(localStorage.getItem('pageCount')) || 0; // 解决bug: 将字符串转换为数字

// 判断是否超过使用次数限制 if (count >= 10) { alert('今天无法再使用本页面!'); location.href = '1.html'; } else { // 更新页面使用次数 localStorage.setItem('pageCount', ++count); }

// 记录今天已经使用过页面 localStorage.setItem('lastVisit', today);

// 优化代码: 将localStorage的操作封装成方法 function getLocalStorageItem(key, defaultValue) { const value = localStorage.getItem(key); return value !== null ? JSON.parse(value) : defaultValue; }

function setLocalStorageItem(key, value) { localStorage.setItem(key, JSON.stringify(value)); }

// 获取当前日期 const today = new Date().toDateString();

// 获取当前页面使用次数 let count = getLocalStorageItem('pageCount', 0);

// 判断是否超过使用次数限制 if (count >= 10) { alert('今天无法再使用本页面!'); location.href = '1.html'; } else { // 更新页面使用次数 setLocalStorageItem('pageCount', ++count); }

// 记录今天已经使用过页面 setLocalStorageItem('lastVisit', today);

JavaScript 代码优化:检测 Bug 并提升 localStorage 使用效率

原文地址: https://www.cveoy.top/t/topic/muJD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录