const getTimes = (date = new Date()) => { const sliceStr = str => 0${str}.slice(-2); const year = date.getFullYear(); const month = sliceStr(date.getMonth() + 1); const day = sliceStr(date.getDate()); const week = daysOfWeek[date.getDay()]; const start = new Date(year, date.getMonth(), date.getDate()); const end = new Date(year, date.getMonth(), date.getDate(), 23, 59, 59); const today = new Date().toLocaleDateString(); return { isToday: new Date(${year}-${month}-${day}).toLocaleDateString() === today, currentDate: date, year, month, day, ymd: ${year}-${month}-${day}, md: ${month}月${day}日, ymdw: ${year}年${month}月${day}日 ${week}, start: start.getTime(), end: end.getTime() } }

优化点:

  1. 使用Date构造函数,避免使用字符串拼接生成日期对象
  2. Date构造函数中的月份需要-1,因为0表示1月
  3. 使用toLocaleDateString()方法获取日期的字符串形式,避免字符串拼接和判断
  4. 将start和end的计算放在返回对象中,避免在对象外部计算
  5. 将temp变量改为直接获取当前时间的Date对象
请优化下这段代码: const getTimes = date = new Date = 	const sliceStr = str = 0$strslice-2;	const year = dategetFullYear;	const month = sliceStrdategetMonth + 1;	const day = sliceStrdategetDate;	const week = d

原文地址: https://www.cveoy.top/t/topic/bhc8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录