Object.getOwnPropertyNames vs Object.keys [英] Object.getOwnPropertyNames vs Object.keys

查看:96
本文介绍了Object.getOwnPropertyNames vs Object.keys的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

javascript中 Object.getOwnPropertyNames Object.keys 之间的区别是什么?还有一些例子值得赞赏。

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

推荐答案

有一点不同。 Object.getOwnPropertyNames(a)返回对象的所有自己的属性 a Object.keys(a)返回所有可枚举的自己的属性。这意味着如果你定义你的对象属性而不使它们中的一些 enumerable:false 这两种方法会给你相同的结果。

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.

这很容易测试:

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

如果定义属性而不提供属性属性描述符(意思是你不使用 Object.defineProperties ),例如:

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 vs Object.keys的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆