9

クラスを for...in ループで使用できるように、javascript クラスに itertor を追加する方法を見つけようとしています。Mozilla の指示に従っても、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__」を出力します!

これを機能させる方法を知っている人はいますか?

4

4 に答える 4