I'm building a complex 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?
The 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With