Skip to content

Instantly share code, notes, and snippets.

@lyuehh
Created November 4, 2012 14:36
Show Gist options
  • Save lyuehh/4012149 to your computer and use it in GitHub Desktop.
Save lyuehh/4012149 to your computer and use it in GitHub Desktop.
遍历js object
// 遍历可枚举的自身属性 Ojbect.keys
(function () {
var propertys = Object.keys(window);
alert(propertys.length); //3
alert(propertys.join("\n")); //window,document,InstallTrigger,除了最后一个是火狐私有的属性,原来window对象只有两个可枚举的自身属性.window属性指向window对象自身,一般没什么用.
})();
// 遍历所有的自身属性
(function () {
var propertys = Object.getOwnPropertyNames(window);
alert(propertys.length); //72
alert(propertys.join("\n")); //Object,Function,eval等等
})();
// 遍历可枚举的自身属性和继承属性
(function () {
var getEnumPropertyNames = function (obj) {
var props = [];
for (prop in obj) {
props.push(prop);
}
return props;
}
var propertys = getEnumPropertyNames(window);
alert(propertys.length); //185
alert(propertys.join("\n")); //addEventListener,onload等等
})();
// 遍历所有的自身属性和继承属性
(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等
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment