这里是业余程序员,这个问题超出了我的工资等级.我正在try 构建一个动态html/css日历,其中单元格根据今天的日期填充.我得到了今天的日期,然后try 添加天数来填充另外13天(通过html元素.innerHTML循环).

如果我try 设置日期(30+2),然后 Select getDate().代码运行良好.Javascript计算出6月在第30天结束,结果是2(7月2日)

But this only works if there's only one call, if I have a loop, or call this code multiple times, then the result is different. Is there some async stuff gumming up the works? Here's code: If you leave the "result2" call and comment the others, works great, but multiple calls, things break and numbers get repeated. Please help!

const theDate = new Date();
    const todaysDate = 30;
    
    theDate.setDate(todaysDate + 1);
    let result1 = theDate.getDate();
    
    theDate.setDate(todaysDate + 2);
    let result2 = theDate.getDate();
    
    theDate.setDate(todaysDate + 3);
    let result3 = theDate.getDate();
    
    theDate.setDate(todaysDate + 4);
    let result4 = theDate.getDate();
    
    console.log(result1);
    console.log(result2);
    console.log(result3);
    console.log(result4);

推荐答案

在回答您的问题时,setDate()函数对您来说表现得非常奇怪,因为每次设置日期时,都是相对于之前的设置进行设置的,所以每次都会增加31、32或33天,而不是1、2或3天.更多信息,请参见@Quentin的精彩回答,这一发现完全是他的,我只想在回答中提及根本原因以及我自己对您问题的解决方法.


如果您只想生成日期,另一种解决方案是:

const dayOfMonth = 30;
const date = new Date();
date.setDate(dayOfMonth);
console.log("Date:", date);

let timestamp = Date.parse(date);

for (let i = 1; i <= 14; i++) {
  const newTimestamp = timestamp + i * (1000 * 60 * 60 * 24);
  const newDate = new Date(newTimestamp);
  console.log("New date:", newDate);
}

此方法将操纵时间戳,并为添加到一天毫秒数的每个时间戳生成新日期.

您可以使用循环中的日期逻辑来填充您提到的日历.

Javascript相关问答推荐

如何使用React渲染器放置根dis?

如何按预期聚合SON数据?

无法将nPM simplex-noise包导入在JS项目中工作

React:未调用useState变量在调试器的事件处理程序中不可用

配置WebAssembly/Emscripten本地生成问题

我的服务工作器没有连接到我的Chrome扩展中的内容脚本.我该怎么解决这个问题?

Html文件和客户端存储的相关问题,有没有可能?

我在Django中的视图中遇到多值键错误

在HTML语言中调用外部JavaScript文件中的函数

在Matter.js中添加从点A到另一个约束的约束

为什么我的自定义元素没有被垃圾回收?

TypeError:无法读取未定义的属性(正在读取';宽度';)

当代码另有说明时,随机放置的圆圈有时会从画布上消失

传递方法VS泛型对象VS事件特定对象

将嵌套数组的元素乘以其深度,输出一个和

如何使用Astro优化大图像?

在渲染turbo流之后滚动到元素

react 路由如何使用从加载器返回的数据

select 2-删除js插入的项目将其保留为选项

TabNavigator和StackNavigator之间的Reaction Native中的导航问题