0

我有一个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 question中看到我不应该使用for in. 但是,如果索引不是不存在的数值for(var i = 0; i<arr.length; i++),我该如何循环呢?this.themeData[i]

4

2 回答 2

2

在对象上使用 for..in 循环很好,您只需要使用 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);
        }
    }
}
于 2012-08-31T10:50:41.103 回答
2

在我看来,使用该for...in方法很好,只需确保检查您正在寻找的属性不是来自原型链的某个地方。

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

如果你不检查hasOwnProperty,你最终会得到继承自的属性Object

于 2012-08-31T10:51:57.367 回答