我试图弄清楚如何将迭代器添加到 javascript 类中,以便可以在 for...in 循环中使用该类。遵循 Mozilla 的指示并不会产生他们声称的结果。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators 给定示例的 Jsfiddle:http: //jsfiddle.net/KQayW/
function Range(low, high){
this.low = low;
this.high = high;
this.current = low;
this.next = function() {
if (this.current > this.range.high)
throw StopIteration;
else
return this.current++;
}
}
function RangeIterator(range){
this.range = range;
this.current = this.range.low;
}
RangeIterator.prototype.next = function(){
if (this.current > this.range.high)
throw StopIteration;
else
return this.current++;
};
Range.prototype.__iterator__ = function(){
return new RangeIterator(this);
};
var range = new Range(3, 5);
for (var i in range)
document.getElementById("test").innerHTML = i+"</br>"; // prints 3, then 4, then 5 in sequence
它不会打印出范围内的数字,而是打印出“__iterator__”!
有谁知道如何让它工作?