it is possible to use a object property for a "for in"-Iteration in JavaScript?
I want write a Bag-Class like this:
var Bag = function () {
this.elements = {};
}
Bag.prototype.add = function (key, value) {
this.elements[key] = value;
};
// other methods ...
Now i want use objects of this class in a for in iteration:
for (var key in myBag) {
console.log(myBag[key]); // or myBag.get(key);
}
It is possible to do this without a helper method like var key in myBag.getAll()?
You could add the key/value pairs to the instance itself, and create the method as non-enumerable, for example:
function Bag() {
}
Object.defineProperty(Bag.prototype, 'add', {
enumerable: false,
value: function(k, v) {
this[k] = v
}
})
var bag = new Bag
bag.add('a',1)
bag.add('b',2)
bag.add('c',3)
for (var k in bag)
console.log(k)
//^ a
// b
// c
Note, that you could also declare the method normally and always loop with hasOwnProperty
check:
for (var k in bag)
if (bag.hasOwnProperty(k))
console.log(k)
Or another alternative:
Object.keys(bag).forEach(function(k) {
console.log(k)
})