最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Alternative for "for of"-loop - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 5

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/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

发布评论

评论列表(0)

  1. 暂无评论