JavaScript薪资倒计时代码优化及类型转换问题咨询
薪资倒计时代码优化与类型转换修复方案
一、正确的数字转字符串方式
无需通过拼接冒号实现类型转换,直接用以下两种原生方式即可:
数字.toString():直接将数字转为字符串,例如10.toString()String(数字):强制类型转换,例如String(10)
如果是需要将数字映射为小写文本(如星期几),不要直接对数字调用toLocaleLowerCase(),而是先把数字映射为对应字符串:
const weekDays = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']; const currentDayStr = weekDays[new Date().getDay()]; // 直接获取小写星期字符串
二、代码简化方案
将发薪日计算、倒计时逻辑拆分为独立函数,消除冗余代码,同时实现瑞士银行周末发薪提前规则:
1. 核心函数封装
// 调整日期:若为周末则提前至最近工作日 function adjustForWeekend(date) { const day = date.getDay(); if (day === 0) date.setDate(date.getDate() - 2); // 周日提前到周五 else if (day === 6) date.setDate(date.getDate() - 1); // 周六提前到周五 return date; } // 获取当月/下月发薪日期(规则:默认23日,周末提前;若当前已过发薪日,取下月日期) function getPayDay() { const now = new Date(); const year = now.getFullYear(); const month = now.getMonth(); let payDay = adjustForWeekend(new Date(year, month, 23)); // 当前日期已过本月发薪日,取下月发薪日 if (now > payDay) { payDay = adjustForWeekend(new Date(year, month + 1, 23)); } return payDay; } // 计算倒计时 function calculateCountdown() { const payDay = getPayDay(); const diff = payDay - new Date(); return { days: String(Math.floor(diff / (1000 * 60 * 60 * 24))).padStart(2, '0'), hours: String(Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))).padStart(2, '0'), minutes: String(Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))).padStart(2, '0'), seconds: String(Math.floor((diff % (1000 * 60)) / 1000)).padStart(2, '0') }; }
2. 调用示例
const countdown = calculateCountdown(); console.log(`距离发薪还有 ${countdown.days}天 ${countdown.hours}时 ${countdown.minutes}分 ${countdown.seconds}秒`);
简化说明
- 将重复的周末判断逻辑抽为独立函数
adjustForWeekend,避免代码冗余 - 发薪日计算与倒计时计算分离,逻辑清晰且便于维护
- 使用
padStart统一补零格式化,无需额外类型转换操作
内容的提问来源于stack exchange,提问作者Spryrix
相关产品推荐
相关产品推荐

