如何修改JavaScript代码实现页面每次加载时递增cookie数值
现有代码的核心问题
- 没有读取浏览器中已存储的对应cookie值,每次调用都传入固定初始值3,因此每次计算得到的都是
3+1=4 - cookie过期时间拼接缺少
max-age=前缀,格式错误会导致cookie无法正常持久化存储 - 逻辑判断错误:当前判断的是
cookieName == null才设初始值,和我们需要的「cookie不存在则设初始值」的逻辑完全不符
修正后的完整代码
// 辅助函数:读取指定名称的cookie值 function getCookie(cookieName) { const name = cookieName + "="; const decodedCookie = decodeURIComponent(document.cookie); const cookieArr = decodedCookie.split(';'); for(let i = 0; i < cookieArr.length; i++) { let c = cookieArr[i].trim(); if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return null; } // 写入cookie并实现递增逻辑 function updateIncrementCookie(cookieName, initialValue = 1, days = 7) { // 先读取已有的cookie值 let currentValue = getCookie(cookieName); let newValue; if (currentValue === null) { // 不存在则用初始值 newValue = initialValue; } else { // 存在则转数字后加1 newValue = parseInt(currentValue, 10) + 1; } // 计算过期时间:天转秒,max-age单位是秒 const maxAge = days * 24 * 60 * 60; // 正确拼接cookie格式 document.cookie = `${cookieName}=${newValue}; max-age=${maxAge}; path=/`; console.log(`${cookieName}: ${newValue}`); } // 页面加载时调用即可实现每次打开页面自动递增 updateIncrementCookie('foo', 1, 7);
关键修改说明
- 新增
getCookie辅助函数,用于读取浏览器中已存储的cookie值,作为递增的基础 - 调整逻辑:先读已有值,不存在才设置初始值,存在就直接+1
- 修正cookie拼接格式,补充
max-age前缀,确保cookie可以按指定时长存储 - 默认参数优化,没传初始值、过期天数时会用默认的1、7天,调用更灵活
内容的提问来源于stack exchange,提问作者equanimity
相关产品推荐
相关产品推荐

