"for of"循环的替代方案

3

我在JavaScript中使用了for-in循环,但我只对键感兴趣。

for(var key in { foo:0, bar:0, blah:0 }) {
    /* do sth. with the key */

}

这个方法可以运行,但是看起来有点愚蠢。Firefox提供了一个for-of循环,但不幸的是它并不能在所有浏览器中运行。我也在Opera 11中测试过它,但是它在那里也不能工作。

// only firefox
for(var key of ["foo", "bar", "blah"]) { 
    /* do sth. with the key */

}

有没有更智能的方法来解决这个问题,适用于所有浏览器?
2个回答

5

除了旧版IE(IE8及以下版本)以外,您可以这样做:

["foo","bar","blah"].forEach(function(key) {
    // do something
});

为了在一些版本的IE中添加支持(我认为IE7和8允许此操作,IE6不支持):
if( ![].forEach) {
    Array.prototype.forEach = function(callback) {
        for( var i=0, l=this.length; i<l; i++) callback(this[i]);
    };
}

+1 我猜如果需要的话,你可以在数组上对其进行原型设计来增加IE 8支持 :-) - TGH

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接