如何在我从可迭代对象中获得的日期列表中包含初始范围值?

How to include the initial range value in this list of dates that I get from an iterable?

我尝试使范围对象成为可迭代对象,以便获取范围限制之间的日期。包括两个日期

let range = {
  from: new Date("2020-01-01"),
  to: new Date("2020-01-10"),
};

range[Symbol.iterator] = function () {
  return {
    current: this.from,
    last: this.to,
    next() {
      if (this.current.getTime() < this.last.getTime()) {
        return {
          done: false,
          value: new Date(this.current.setDate(this.current.getDate() + 1)),
        };
      }

      return { done: true };
    },
  };
};

for (const iterator of range) {
  console.log(iterator);
}

console.log(Array.from(range));

我尝试做但没有成功的是范围的开始日期包含在日期列表中,在本例中为 2020-01-01

关于for..of

当前结果

2020-01-02T00:00:00.000Z
2020-01-03T00:00:00.000Z
2020-01-04T00:00:00.000Z
2020-01-05T00:00:00.000Z
2020-01-06T00:00:00.000Z
2020-01-07T00:00:00.000Z
2020-01-08T00:00:00.000Z
2020-01-09T00:00:00.000Z
2020-01-10T00:00:00.000Z

预期结果

2020-01-01T00:00:00.000Z <-- initial value
2020-01-02T00:00:00.000Z
2020-01-03T00:00:00.000Z
2020-01-04T00:00:00.000Z
2020-01-05T00:00:00.000Z
2020-01-06T00:00:00.000Z
2020-01-07T00:00:00.000Z
2020-01-08T00:00:00.000Z
2020-01-09T00:00:00.000Z
2020-01-10T00:00:00.000Z

关于Array.from

当前结果

[]

预期结果

[2020-01-01T00:00:00.000Z, 2020-01-02T00:00:00.000Z..., 2020-01-10T00:00:00.000Z]

我的另一个问题是为什么在使用 Array.from(range) 时我希望得到日​​期范围内的数组,但它 returns 是一个空数组

更新 0

这是相同的练习,仅使用整数并使用 for..ofArray.from 我得到了预期的结果

https://jsfiddle.net/atd94h0L/

How to include the initial range value in this list of dates that I get from an iterable?

生成初始值,而不是更新后的当前值。

Why when using Array.from(range) it returns an empty array?

因为您的代码确实修改了 range.from 日期对象。循环遍历范围后,它已经用完了,range.from (== range.current) 是 >=range.to`.

所以要解决这两个问题:

let range = {
  from: new Date("2020-01-01"),
  to: new Date("2020-01-10"),
};

range[Symbol.iterator] = function () {
  return {
    current: this.from,
    last: this.to,
    next() {
      const cur = this.current;
      if (cur < this.last) {
        this.current = new Date(cur);
//                     ^^^^^^^^
        this.current.setDate(cur.getDate() + 1)
        return {
          done: false,
          value: cur,
        };
      }

      return { done: true };
    },
  };
};

for (const iterator of range) {
  console.log(iterator);
}

console.log(Array.from(range));