-3

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

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])
        }
    }
}
4

1 回答 1

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测试:

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

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

于 2012-08-20T03:03:47.253 回答