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

JS实现每周循环显示对应数字问题排查:仅显示首日数字

问题排查与修复

核心错误点

  • localStorage存储值错误:初始化时把字符串'now'存入了localStorage,而非变量now的实际毫秒数值;dateWeekEnd的计算是字符串拼接'now'+'week',完全不符合时间计算逻辑,后续转数字时会得到NaN,导致所有判断失效,只能走default返回day1。
  • 日期计算逻辑错误:原代码试图用dateWeekEnd - date计算周数,但dateWeekEnd本身存储错误,且逻辑上应该计算当前时间与初始存储日期的时间差,再转换为天数取模7,以此匹配每周循环的星期对应关系,而非计算周数。
  • 时间单位错误:原代码中week变量仅计算了秒数(606024*7),但Date.now()返回的是毫秒数,两者单位不匹配,无法正确计算时间差。
  • switch分支逻辑错误:即使周数计算正确,case 1到7也无法对应星期几的循环需求,应该基于天数取模后的0-6值来匹配对应的day参数。

修正后的代码

const Content = {};

Content.makeNumber = function (day1, day2, day3, day4, day5, day6, day7) {
    const weekMs = 60 * 60 * 24 * 7 * 1000; // 一周的毫秒数
    const dayMs = 60 * 60 * 24 * 1000; // 一天的毫秒数
    let initialDate = localStorage.getItem("date");

    // 首次访问初始化存储
    if (initialDate === null) {
        const now = Date.now();
        localStorage.setItem('date', now.toString());
        initialDate = now.toString();
    }

    const initialMs = Number(initialDate);
    const currentMs = Date.now();
    // 计算当前时间与初始日期的天数差,取模7得到0-6的循环值
    const dayDiff = Math.floor((currentMs - initialMs) / dayMs) % 7;

    // 根据天数差匹配对应数字
    switch (dayDiff) {
        case 0:
            return day1;
        case 1:
            return day2;
        case 2:
            return day3;
        case 3:
            return day4;
        case 4:
            return day5;
        case 5:
            return day6;
        case 6:
            return day7;
        default:
            return day1;
    }
};

export default Content;

逻辑说明

  • 首次访问页面时,将当前时间的毫秒数存入localStorage,作为循环的起始基准。
  • 后续每次调用方法时,计算当前时间与起始基准的天数差,通过取模7实现每周循环的效果。
  • 确保刷新页面后,localStorage保留的起始基准不会丢失,能继续匹配对应日期的数字。

内容的提问来源于stack exchange,提问作者mau54live

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 04:39:25