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?
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?
Share Improve this question edited Jul 25, 2013 at 5:36 jdero 1,8173 gold badges23 silver badges36 bronze badges asked Jul 25, 2013 at 5:33 ortwicortwic 832 silver badges8 bronze badges2 Answers
Reset to default 5In 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/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