【JavaScript】属性名的遍历的方法区别forin,Object.keys,OwnProperty,Reflect.ownKeys

var obj = {
name:'kkk',
age:88, 
is: true,
99:100,
[Symbol()]:"symbol"
}
Object.prototype.addone = "one" // 给obj所继承的构造函数添加原型addone

Object.defineProperty(obj,"name",{
	enumerable: false }) // 将obj的name属性改为不可枚举
	
for (var item in obj){ console.log(item)} // 99,age,is,addone
for (var item in Object) {console.log(item)} //undefined  Object没有可枚举属性

Object.keys(obj)
//(3) ["99", "age", "is"] addone非自身,除symbol,name非枚举
Object.keys(Object)
//[]

Object.getOwnPropertyNames(obj)
//(4) ["99", "name", "age", "is"]
Object.getOwnPropertyNames(Object)
//(24) ["length", "name", "prototype", "assign", "getOwnPropertyDescriptor", "getOwnPropertyDescriptors", "getOwnPropertyNames", "getOwnPropertySymbols", "is", "preventExtensions", "seal", "create", "defineProperties", "defineProperty", "freeze", "getPrototypeOf", "setPrototypeOf", "isExtensible", "isFrozen", "isSealed", "keys", "entries", "values", "fromEntries"]

Object.getOwnPropertySymbols(obj)
//[Symbol()]
Object.getOwnPropertySymbols(Object)
//[]

Reflect.ownKeys(obj)
//(5) ["99", "name", "age", "is", Symbol()]
Reflect.ownKeys(Object)
//(24) ["length", "name", "prototype", "assign", "getOwnPropertyDescriptor", "getOwnPropertyDescriptors", "getOwnPropertyNames", "getOwnPropertySymbols", "is", "preventExtensions", "seal", "create", "defineProperties", "defineProperty", "freeze", "getPrototypeOf", "setPrototypeOf", "isExtensible", "isFrozen", "isSealed", "keys", "entries", "values", "fromEntries"]
  1. for in :可枚举属性, 继承自原型的属性的可枚举属性( 基本包装类型的原型属性是不可枚举的),symbol类型除外
    ?? js中基本包装类型的原型属性是不可枚举的,如Object, Array, Number等???这里的疑问是很多人都是这么写的,但是基本包装类型不是 String, Boolean,Number吗?
    拓展:可枚举和不可枚举属性 (参考Object.defineProperty() )

  2. Object.keys : 自有可枚举属性名,除symobl

  3. Object.getOwnPropertyNames() :自身所有属性,除symbol

  4. Object.getOwnPropertySymbols() :自身所有symbol类型属性

  5. Reflect.ownKeys(obj) :自身所有属性,包括symbol,包括不可枚举,相当于 Object.getOwnPropertyNames + Object.getOwnPropertySymbols

你可能感兴趣的:(js)