You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

设置JavaScript Cookie的代码错误及ESLint超时问题求助

修复Cookie弹窗代码的ESLint错误与规范问题

核心问题分析与解决步骤

  1. ESLint超时错误:原代码重复声明了writeCookie、readCookie、alert1三个函数(先空声明再重新定义),这会导致解析混乱,直接删除空的函数声明即可解决超时问题。

  2. 代码规范修复:针对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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 06:44:52