Best way to encode an iterator in javascript

I am creating a complex object in Javascript, and I want to set an iterator over the internal collection of the object.

The only way I can think of is the usual way to expose iterators in prototype.js:

customObject.each(function (item) { ... })

with the provided function called by the iterator, each for each element in the collection, one after the other.

Do you know any other reliable way? Maybe this will allow users to use the usual foreach construct?

+5
source share
2 answers

The prototype style function is a good option, although you may 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]);
        }
    }

}
}();

, ( )

, , each, , , , - (, )

Edit

+6

for in.

>>> var customObject = {x: 1, y:2}
>>> for (a in customObject) console.log(a, customObject[a])
x 1
y 2

.

>>>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
+1

All Articles