设置JavaScript Cookie的代码错误及ESLint超时问题求助
核心问题分析与解决步骤
ESLint超时错误:原代码重复声明了
writeCookie、readCookie、alert1三个函数(先空声明再重新定义),这会导致解析混乱,直接删除空的函数声明即可解决超时问题。代码规范修复:针对Brackets检测出的51个问题,逐一修正如下:
- 添加
'use strict'严格模式,提升代码安全性 - 统一使用4空格缩进,修正所有缩进位置错误
- 修正函数括号与大括号的空格(
)后加空格再跟{) - 合并变量声明,逗号后添加空格
- 替换
!=/==为严格相等的!==/=== - 声明未定义的变量
end - 替换已废弃的
escape/unescape为标准的encodeURIComponent/decodeURIComponent - 为单条语句的
if添加块级大括号,符合规范 - 修正警告弹窗字符串中的拼写错误(
\Please改为\n Please) - 补全所有语句末尾的分号
- 添加
修正后的完整代码
'use strict'; function writeCookie(name, value, hours) { let expire = ''; if (hours !== null) { expire = new Date(Date.now() + hours * 3600000); expire = `; expires=${expire.toGMTString()}`; } document.cookie = `${name}=${encodeURIComponent(value)}${expire}`; } function readCookie(name) { let cookieValue = ''; const search = `${name}=`; if (document.cookie.length > 0) { const offset = document.cookie.indexOf(search); if (offset !== -1) { let end = document.cookie.indexOf(';', offset + search.length); if (end === -1) { end = document.cookie.length; } cookieValue = decodeURIComponent(document.cookie.substring(offset + search.length, end)); } } return cookieValue; } function alert1() { const seen = readCookie('viewed'); if (seen !== 'yes') { if (confirm('***WARNING*** \n Some of these jokes MAY be offensive. \n \n If you do not wish to be offended \n Please Press Cancel to return \n \n Please note this will place a cookie on your computer')) { writeCookie('viewed', 'yes', 9999); } else { window.location = 'index.htm'; } } }
关键修复点说明
- 移除重复的空函数声明,解决ESLint超时问题
- 使用模板字符串替代字符串拼接,提升可读性
- 用
Date.now()替代(new Date()).getTime(),更简洁 - 变量声明使用
let/const替代var,符合现代JS规范 - 修正所有空格、缩进、符号使用的规范问题
内容的提问来源于stack exchange,提问作者Eugene Donaghy
相关产品推荐
相关产品推荐

