编辑代码

class Range {
    constructor(from, to) {
        this.from = from;
        this.to = to;
    }
    has(x) {
        return typeof x === 'number' && this.from <= x && x <= this.to;
    }
    //使用集合表示法返回当前范围的字符串表示
    toString() {
        return `{ x | ${this.from} <= x <= ${this.to}}`;
    }
    [Symbol.iterator]() {
        let next = Math.ceil(this.from);
        let last = this.to;
        return {
            //迭代器对象
            next() {
                return (next <= last) ? { value: next++ } : { done: true }
            },
            //迭代器本身也可以迭代
            [Symbol.iterator]() {
                return this;
            }
        }
    }
}
const obj = new Range(1, 10);
for (let x of obj) {
    console.log(x);
}
console.log(obj.has(5));
console.log(obj.toString());