在Javascript中迭代对象属性

时间:2014-11-24 06:34:39

标签: javascript object for-loop iteration

我在javasript对象中有一组属性。

    var leanToolButtonStatus = {
    FiveSStatus:0,
    SmallLotStatus:0,
    SmedStatus:0,
    QualityStatus:0,
    CellsStatus:0,
    CrossTrainStatus:0,
    SelfDirectedStatus:0,
    PMStatus:0,
    VendorStatus:0,
    SmallPurchaseStatus:0,
    NewEquipmentStatus:0,
    MarketStatus:0,
    KanbanStatus:0
}

现在我想运行一个for-loop来迭代,所以我尝试了:

  function loopThroughObject(){
    var iterationCounter = 0;
    for(var x = 0; x<1; x++){
        for(var y = 0; y<6; y++){
        switch(leanToolButtonStatus[iterationCounter]) {
            case 0:
                break;
            case 1:
                break;
            case 2:
                break;
            }
        }
        iterationCounter++;
    }
}

但是我收到以下错误:

Uncaught SyntaxError: Unexpected number.

我出错的任何想法?

3 个答案:

答案 0 :(得分:2)

如果对象的结构与您在问题中添加的结构完全相同,则不需要循环,只需将其访问为:

var leanToolButtonStatus = {
    FiveSStatus:0,
    SmallLotStatus:0,
    SmedStatus:0,
    QualityStatus:0,
    CellsStatus:0,
    CrossTrainStatus:0,
    SelfDirectedStatus:0,
    PMStatus:0,
    VendorStatus:0,
    SmallPurchaseStatus:0,
    NewEquipmentStatus:0,
    MarketStatus:0,
    KanbanStatus:0
};
console.log(leanToolButtonStatus["FiveSStatus"]);

如果您不知道密钥名称。您可以使用for..in循环,如:

for(val in leanToolButtonStatus ) {
    console.log(leanToolButtonStatus[val]);
}

答案 1 :(得分:2)

它应该与此代码邮箱一起使用:

for(key in list)
{
 var elementOfList = list[key];
}

键可以是&#39; FiveSStatus&#39;和elementOfList 0

答案 2 :(得分:1)

#1
for (var key in leanToolButtonStatus) {
   leanToolButtonStatus[key]
}

#2
Object.keys(leanToolButtonStatus).forEach(function (key) {
    leanToolButtonStatus[key]
});