Object.getOwnPropertyNames()
Object.getOwnPropertyNames()
Object.getOwnPropertyNames()
方法, 返回一个字符串数组,由指定对象的所有自身属性的属性名组成。包括不可枚举属性但不包括Symbol值作为名称的属性。
数组中枚举属性的顺序与通过 for...in
循环(或 Object.keys
)迭代该对象属性时一致。
数组中不可枚举属性的顺序未定义。
1 2 3 |
// 语法: Object.getOwnPropertyNames(obj) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
var arr = ["a", "b", "c"]; console.log(Object.getOwnPropertyNames(arr).sort()); // ["0", "1", "2", "length"] // 类数组对象 var obj = { 0: "a", 1: "b", 2: "c"}; console.log(Object.getOwnPropertyNames(obj).sort()); // ["0", "1", "2"] // 使用Array.forEach输出属性名和属性值 Object.getOwnPropertyNames(obj).forEach(function(val, idx, array) { console.log(val + " -> " + obj[val]); }); // 输出 // 0 -> a // 1 -> b // 2 -> c //不可枚举属性 var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; }, enumerable: false } }); my_obj.foo = 1; console.log(Object.getOwnPropertyNames(my_obj).sort()); // ["foo", "getFoo"] |
注意,如果只需要可枚举属性,使用Object.keys
或用for...in
循环即可(还会获取到原型链上的可枚举属性,不过可以使用hasOwnProperty()
方法过滤掉)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Object.getOwnPropertyNames() 不会获取原型链上的属性 function ParentClass() {} ParentClass.prototype.inheritedMethod = function() {}; function ChildClass() { this.prop = 5; this.method = function() {}; } ChildClass.prototype = new ParentClass; ChildClass.prototype.prototypeMethod = function() {}; console.log( Object.getOwnPropertyNames( new ChildClass() // ["prop", "method"] ) ); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
var target = myObject; var enum_and_nonenum = Object.getOwnPropertyNames(target); var enum_only = Object.keys(target); // 只获取不可枚举的属性 var nonenum_only = enum_and_nonenum.filter(function(key) { var indexInEnum = enum_only.indexOf(key); if (indexInEnum == -1) { // 没有发现在enum_only健集中意味着这个健是不可枚举的, // 因此返回true 以便让它保持在过滤结果中 return true; } else { return false; } }); console.log(nonenum_only); |