I got a for-in loop in JavaScript, but I'm only interested in the keys
for(var key in { foo:0, bar:0, blah:0 }) {
/* do sth. with the key */
}
This works, but it looks a little bit stupid. Firefox offers a for-of loop. Unfortunately it doesn't work in all browsers. I also tested it in Opera 11 and it doesn't work there.
// only firefox
for(var key of ["foo", "bar", "blah"]) {
/* do sth. with the key */
}
Is there any smarter way to solve this for every browser?
In anything except old IE (IE8 and older), you can do this:
["foo","bar","blah"].forEach(function(key) {
// do something
});
To add support in some versions of IE (I think IE7 and 8 allow this, IE6 does not):
if( ![].forEach) {
Array.prototype.forEach = function(callback) {
for( var i=0, l=this.length; i<l; i++) callback(this[i]);
};
}
Try to use Object.keys that will allow you to get only that part.
You can read more about here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
(Remember all associative arrays in javascript are objects)
Keep in mind is only supported on IE >= 9
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