Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative for "for of"-loop

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?

like image 904
ortwic Avatar asked Oct 28 '25 00:10

ortwic


2 Answers

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]);
    };
}
like image 115
Niet the Dark Absol Avatar answered Oct 29 '25 13:10

Niet the Dark Absol


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

like image 20
chris-l Avatar answered Oct 29 '25 13:10

chris-l