我应该如何循环通过和“;关联对象“;在javascript中

How should I loop through and "associative object" in javascript?

本文关键字:关联 对象 javascript 何循环 循环 我应该      更新时间:2023-09-26

我有一个对象this.themeData,类似于这样(显示控制台输出)

Object
    Banner: Object
        property: "null"
        raw: "uploads/1/somefile.png"
        selector: "null"
        value: "../../uploads/1/somefile.png"
        __proto__: Object
    H1_FontSize: Object
    H2_FontColor: Object
    H2_FontSize: Object

我这样循环:

    for (attrName in this.themeData) {
        attrData = this.themeData[attrName];
        if (attrData.selector && attrData.value) {
            $(".SomeSelector").css(attrData.property, attrData.value);
        }
    }

这是有效的,但我在最近的一个SO问题中看到,我不应该使用for in。但是,如果索引不是数值for(var i = 0; i<arr.length; i++),而this.themeData[i]不存在,我该如何循环?

可以用于。。在对象上的循环中,您只需要使用hasOwnProperty()检查来过滤它们

for (attrName in this.themeData) {
    if (this.themeData.hasOwnProperty(attrName)) {
        attrData = this.themeData[attrName];
        if (attrData.selector && attrData.value) {
            $(".SomeSelector").css(attrData.property, attrData.value);
        }
    }
}

在我看来,使用for...in方法是可以的,只需确保检查您要查找的属性不是来自原型链的某个位置。

var foo = Object();
for(item in foo) {
  if(foo.hasOwnProperty(item) {
      alert(item); // The key
      alert(foo[item]); // The value.
  }
}

如果不选中hasOwnProperty,则最终会得到从Object继承的属性。