admin管理员组文章数量:1296885
I'm building a plex object in Javascript and I want to expose an iterator over an internal collection of the object.
The only way I can think of is the usual way of exposing iterators in prototype.js :
customObject.each(function (item) { ... })
with the provided function being called by the iterator each for every item in the collection, one after the other.
Do you know any other reliable way? Maybe a way that would let users use the usual foreach construct?
I'm building a plex object in Javascript and I want to expose an iterator over an internal collection of the object.
The only way I can think of is the usual way of exposing iterators in prototype.js :
customObject.each(function (item) { ... })
with the provided function being called by the iterator each for every item in the collection, one after the other.
Do you know any other reliable way? Maybe a way that would let users use the usual foreach construct?
Share edited Oct 16, 2009 at 23:24 jfs 415k205 gold badges1k silver badges1.7k bronze badges asked Oct 15, 2009 at 10:51 AlsciendeAlsciende 27k9 gold badges53 silver badges68 bronze badges2 Answers
Reset to default 6The prototype style function is a good option, though you might also consider something like:
overlayRegistry = function() {
var overlays = [];
var index = 0;
return {
addOverlay : function(overlay) {
overlays.push(overlay);
count : function() {
return overlays.length;
},
reset : function() {
index = 0;
},
next : function() {
if (index < overlays.length) {
return overlays[index++];
} else {
return null;
}
},
each : function (callback) {
for (var index = 0, length = overlays.length; index < length; ++index) {
callback(overlays[index]);
}
}
}
}();
In this case, you can iterate over it in steps while you wait for other events (as was the case behind this structure)
Basically, providing a method like each
can work great if all you need is simple iteration, but if you need more control, then something like the above would work (of course, you could do both)
Edit
Added each method
You should use for in
instead.
>>> var customObject = {x: 1, y:2} >>> for (a in customObject) console.log(a, customObject[a]) x 1 y 2
But remember about inherited properties.
>>>Object.prototype.yarrr = function yarrr(){ console.warn('YARRR!') } >>> for (a in customObject) console.log(a, customObject[a]) x 1 y 2 yarrr() >>> for (a in customObject) if (customObject.hasOwnProperty(a)) console.log(customObject[a]) x 1 y 2
本文标签: Best way to code iterator in javascriptStack Overflow
版权声明:本文标题:Best way to code iterator in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741646218a2390198.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论