我想弄清楚如何将一个itertor添加到一个JavaScript类,使得该类可以用于for ... in循环中。遵循Mozilla的指示不会产生他们声称的结果。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators 的jsfiddle给出例子:http://jsfiddle.net/KQayW/将一个自定义迭代器添加到一个javascript类
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__”!
有谁知道如何让这个工作?
哈。谢谢!我想我没有仔细阅读。 – anonymouse