Object.getOwnPropertyNames vs Object.keys

What's the difference between Object.getOwnPropertyNames and Object.keys in javascript? Also some examples would be appreciated.


There is a little difference. Object.getOwnPropertyNames(a) returns all own properties of the object a . Object.keys(a) returns all enumerable own properties. It means that if you define your object properties without making some of them enumerable: false these two methods will give you the same result.

It's easy to test:

var a = {};
Object.defineProperties(a, {
    one: {enumerable: true, value: 'one'},
    two: {enumerable: false, value: 'two'},
});
Object.keys(a); // ["one"]
Object.getOwnPropertyNames(a); // ["one", "two"]

If you define a property without providing property attributes descriptor (meaning you don't use Object.defineProperties ), for example:

a.test = 21;

then such property becomes an enumerable automatically and both methods produce the same array.


另一个区别是数组Object.getOwnPropertyNames方法将返回一个额外的length属性。

var x = ["a", "b", "c", "d"];
Object.keys(x);  //[ '0', '1', '2', '3' ]
Object.getOwnPropertyNames(x);  //[ '0', '1', '2', '3', 'length' ]

另一个区别是(至少与nodejs)“getOwnPropertyNames”函数不能保证键的顺序,这就是为什么我通常使用“键”功能:

    Object.keys(o).forEach(function(k) {
      if (!o.propertyIsEnumerable(k)) return;
      // do something...
    });
链接地址: http://www.djcxy.com/p/31742.html

上一篇: 预览Git推送

下一篇: Object.getOwnPropertyNames与Object.keys