如何遍历对象的属性

167 阅读1分钟
  • 遍历自身可枚举的属性(可枚举,非继承)
    Object.keys()
  • 遍历自身所有的属性(可枚举,不可枚举,非继承属性)
    Object.getOwnPropertyNames() 
  • 遍历可枚举的自身属性和继承属性(可枚举,可继承)
    for in
  • 遍历自身所有的属性

(function () {

    var getAllPropertyNames = function (obj) {

    var props = [];

    do {

        props = props.concat(Object.getOwnPropertyNames(obj));

        } while (obj = Object.getPrototypeOf(obj));

     return props;

    }

    var propertys = getAllPropertyNames(window);

    alert(propertys.length); //276

    alert(propertys.join("\n")); //toString 等

})()