描述

Object.getOwnPropertyNames() 返回一个数组,该数组对元素是 obj自身拥有的枚举或不可枚举属性名称字符串。 数组中枚举属性的顺序与通过 for…in 循环(或 Object.keys)迭代该对象属性时一致。数组中不可枚举属性的顺序未定义。

该方法不会获取到原型链上的属性:

示例

使用 Object.getOwnPropertyNames())

  1. var arr = ["a", "b", "c"];
  2. console.log(Object.getOwnPropertyNames(arr).sort()); // ["0", "1", "2", "length"]
  3. // 类数组对象
  4. var obj = { 0: "a", 1: "b", 2: "c"};
  5. console.log(Object.getOwnPropertyNames(obj).sort()); // ["0", "1", "2"]
  6. // 使用Array.forEach输出属性名和属性值
  7. Object.getOwnPropertyNames(obj).forEach(function(val, idx, array) {
  8. console.log(val + " -> " + obj[val]);
  9. });
  10. // 输出
  11. // 0 -> a
  12. // 1 -> b
  13. // 2 -> c
  14. //不可枚举属性
  15. var my_obj = Object.create({}, {
  16. getFoo: {
  17. value: function() { return this.foo; },
  18. enumerable: false
  19. }
  20. });
  21. my_obj.foo = 1;
  22. console.log(Object.getOwnPropertyNames(my_obj).sort()); // ["foo", "getFoo"]

下面的例子演示了该方法不会获取到原型链上的属性:

  1. function ParentClass() {}
  2. ParentClass.prototype.inheritedMethod = function() {};
  3. function ChildClass() {
  4. this.prop = 5;
  5. this.method = function() {};
  6. }
  7. ChildClass.prototype = new ParentClass;
  8. ChildClass.prototype.prototypeMethod = function() {};
  9. console.log(
  10. Object.getOwnPropertyNames(
  11. new ChildClass() // ["prop", "method"]
  12. )
  13. );

只获取不可枚举的属性