Javascript 迭代日期的iterable对象时的结果不正确
日期范围很广的Javascript 迭代日期的iterable对象时的结果不正确,javascript,date,ecmascript-6,iterator,iterable,Javascript,Date,Ecmascript 6,Iterator,Iterable,日期范围很广的 const dateRange = { from: new Date(2018, 0, 23), to: new Date(2018, 0, 28), [Symbol.iterator]() { this.current = this.from return this }, next() { if (this.current <= this.to) { this
const dateRange = {
from: new Date(2018, 0, 23),
to: new Date(2018, 0, 28),
[Symbol.iterator]() {
this.current = this.from
return this
},
next() {
if (this.current <= this.to) {
this.current.setDate(this.current.getDate() + 1)
return {done: false, value: this.current}
}
return {done: true}
}
}
当console.log(dateList)
我得到以下输出
[ 2018-01-29T06:00:00.000Z,
2018-01-29T06:00:00.000Z,
2018-01-29T06:00:00.000Z,
2018-01-29T06:00:00.000Z,
2018-01-29T06:00:00.000Z,
2018-01-29T06:00:00.000Z ]
在日期列表上使用forEach进行迭代也会给出错误的结果
dateList.forEach(date => {
console.log(date)
})
2018-01-29T06:00:00.000Z
2018-01-29T06:00:00.000Z
2018-01-29T06:00:00.000Z
2018-01-29T06:00:00.000Z
2018-01-29T06:00:00.000Z
2018-01-29T06:00:00.000Z
但是迭代iterable对象会得到例外的结果
for (let date of dateRange) {
console.log(date)
}
2018-01-24T06:00:00.000Z
2018-01-25T06:00:00.000Z
2018-01-26T06:00:00.000Z
2018-01-27T06:00:00.000Z
2018-01-28T06:00:00.000Z
2018-01-29T06:00:00.000Z
const numberList = Array.from(range)
console.log(numberList)
[ 1, 2, 3, 4, 5 ]
为了给问题提供背景
我举的下一个iterable的例子几乎是同一个例子。不同之处在于,在这种情况下,它与数字有关
let range = {
from: 1,
to: 5
};
range[Symbol.iterator] = function() {
return {
current: this.from,
last: this.to,
next() {
if (this.current <= this.last) {
return { done: false, value: this.current++ };
} else {
return { done: true };
}
}
};
};
这让我假设,我增加日期的方式产生了这个结果,如果是这样,我还有什么选择呢?再次感谢
你能解释一下错误的原因吗?非常感谢。您是通过引用创建数组索引,而不是通过值创建数组索引
这意味着您的数组基本上是一系列“指针”,它们只是对同一个对象的相等引用(多亏了@rock star)
所有数组成员共享同一个日期对象,因此一旦它到达控制台,它们都将显示最近的变异<代码>返回{done:false,value:newdate(this.current)}
关于更新,对象和原语之间有很大的区别。原语是不可变的,并在赋值时进行处理。对于对象,它不会复制对象本身,而只是对对象的引用,并且对象是可变的。所以原因仍然是,你将对同一个对象的多个引用放入数组中,所以很自然地,通过所有引用可以看到其中一个引用的突变。我理解你的解释。基于这个事实。我怎样才能得到预期的结果呢?在我的第一条注释中使用代码。真的,我现在就检查它。你是对的,只是说最后一条注释保留了实际值很奇怪。相反,它们只是对同一对象的相等引用。
const numberList = Array.from(range)
console.log(numberList)
[ 1, 2, 3, 4, 5 ]