我有一个 Vue js 前端,其中有以下 while 循环:
while (this.day.getDay() != 0) {
console.log(this.day)
this.days.push(this.day)
this.dates.push(this.day.toDateString())
this.day.setDate(this.day.getDate() + 1)
}
我将变量实例化为:
day: new Date(Date.now()),
dates: [],
days:[]
我想知道为什么日期数组工作正常并包含 sep 6、sep7 和 sep 8,但 days 数组只有 sep 09 三次?同样奇怪的是,当我记录 this.day 时,它会记录正确的天数,但不会将其添加到 days 数组中。这是怎么回事?
最佳答案
当你执行这一行时:
this.days.push(this.day)
您每次都会持续推送相同的 Date 对象。您永远不会重新分配 this.day
,您只需使用 setDate
对其进行更改,并且每次执行此操作时,该数组中的所有引用都会更新。
但是当你运行这一行时:
this.dates.push(this.day.toDateString())
您正在捕获按下时的状态,字符串是不可变的。
有关您所获得的内容的更简单示例,请查看此
const foo = {bar: 3};
const arr = [foo, foo, foo]; // all the same foo
arr.map(x => x.bar); // 3, 3, 3
foo.bar = 5;
arr.map(x => x.bar); // 5, 5, 5
关于Javascript 日期有两种不同的行为方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52211757/