测试对象属性的方式
1. in操作符
in操作符左边是一个属性名,右边是一个对象。如果对象包含相应名字的自有属性或继承属性,返回true
let o = { x:1};
“x” in o; //true
“y” in o; //false
“toString” in o; //true
2. hasOwnProperty()
用于测试对象是否有给定名字的属性。对继承的属性,返回false
let o = {x:1};
o.hasOwnProperty(“x”); //true
o.hasOwnProperty(“y”); //false
o.hasOwnproperty(“toString”); //false
3. propertyIsEnumerable()
如果传入的命名属性是自有属性其这个属性的enumerable特性为true,则返回true。使用常规js代码创建的属性都是可枚举的。
let o ={x:1};
o.propertyIsEnumerable(“x”); //true
o.perpertyIsEnumerable(“toString”); //false
Object.prototype.perpertyIsEnumerable(“toString”); //false
4. !==
最简单的属性查询,未定义的属性返回false
let o ={x:1}
o.x !== undefined; //true
o.y !== undefined; //false
o.toString !==undefined; //true
枚举属性
除了使用for/in循环对指定对象进行枚举外,js还提供了几种枚举方法。
1. Object.keys()
之返回对象可枚举自有属性的数组
2. Object.getOwnPropertyNames()
除了会返回可枚举的自有属性外,还返回不可枚举自有属性名的数组。只要它的名字是字符串。
3. Object.getOwnPropertySymbols()
返回名字是符号的自有属性,无论是否可枚举
4. Reflect.ownKeys()
返回所有属性名。(可枚举、不可枚举、字符串属性、符号属性)