javascript:对具有对象并读取它们的对象进行排序

时间:2012-08-20 02:05:30

标签: javascript

如何读取此代码以读取对象,并且能够读取其中的对象:

var book = {
    "main title": "Javascript",
    "sub-title": "Def Guide",
    "for": "all audiences",
    author: {
        firstname: "David",
        surname: "Fatagans"
    }
};

for (propName in book){
    console.log("key: " + propName + " value: " + book[propName]);
    if (typeof book[propName] === "object"){
        for (innerObject in book[propName]){
            console.log("key: " + innerObject + "value: " + book[propName][innerObject])
        }
    }
}

1 个答案:

答案 0 :(得分:0)

一种方法是将代码放入函数中并递归调用它,例如:

function printObject(obj) {
  for (var propName in obj) {
    console.log("key: " + propName + " value: " + obj[propName]);

    if (typeof obj[propName] == "object") {
        printObject(obj);
    }
  }
}

以上内容还将显示对象的[[Prototype]]链上的可枚举属性。要忽略这些,请使用 hasOwnProperty test:

  if (obj.hasOwnProperty(propName)) {
    // propName is not inherited
  }

小心将主机对象(例如DOM元素)传递给函数,需要采取额外的预防措施。