Created
November 4, 2012 14:36
-
-
Save lyuehh/4012149 to your computer and use it in GitHub Desktop.
遍历js object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 遍历可枚举的自身属性 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