ano*_*use 7 javascript iterator for-in-loop
我试图找出如何将一个迭代器添加到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
Run Code Online (Sandbox Code Playgroud)
它不打印范围内的数字,它打印出"__iterator__"!
有谁知道如何让这个工作?
小智 7
使用ES2015简单:
function Range(start, end) {
var ret = {};
ret[Symbol.iterator] = function *() {
while (start < end)
yield start++;
}
return ret;
}
Run Code Online (Sandbox Code Playgroud)
虽然你必须使用:
for (var x of Range(1, 10))
Run Code Online (Sandbox Code Playgroud)
使用 ES2015 可以更简单
const Range = (start, end) => ({
*[Symbol.iterator]() {
while (start < end)
yield start++;
}
})
for (var x of Range(1, 10)) {
console.log(x)
}
Run Code Online (Sandbox Code Playgroud)
小智 3
Mozilla 文档指出,迭代器功能是在 JavaScript 1.7 中引入的。尽管 Chrome 从 1.7 开始就支持一些功能,但并未完全支持,因此这不起作用。如果您在最新的 Firefox 版本中测试您的代码,您会发现它可以工作。
尽管您可能想要附加范围值而不是替换整个 div。
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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3164 次 |
最近记录: |