JavaScript 对象属性检查方法

     JS 对象可以看做属性的集合,我们经常会检测集合中成员的属性关系——判断某个属性是否存在于对象中。可以通过in运算符、hasOwnPreperty() propertyIsEnumerable() 方法来完成这个工作,甚至仅通过属性查询也可以做到这一点。

    in运算符的左侧是属性名(字符串),右侧是对象。如果对象的自有属性或继承属性中包含这个属性则返回true。

let o = {x: 1}
'x' in o; // true 'x'是0的属性
'y' in o; // false 'y'不是o的属性
'toString' in o; // true 'o' 继承 'toString'属性

    对象的hasOwnProperty() 方法用来检测给定的名字是否是对象的自有属性。对于继承属性他将返回false;

let b = {x: 1}
b.hasOwnProperty('x'); // true; b有一个自有属性x
b.hasOwnProperty('y'); // false; b中不存在属性y
b.hasOwnProperty('toString'); // false; toString是继承属性

    propertyIsEnumerable() hasOwnProperty()是增强版,只有检测到是自有属性且这个属性的可枚举为true是才返回true。某些内置属性是不可枚举的。通过由JavaScript代码创建的属性都是可枚举的,除非在ECMAScript 5 中使用一个特殊的方法来改变属性的可枚举性;

let f = {p: 1}
let p = f.prototype = {z: 2};
p.x = 1;
console.log(p.propertyIsEnumerable('x')); // true; p中有一个可枚举的自有属性x;
console.log(p.propertyIsEnumerable('p')); // false; y是继承来的
console.log(Object.prototype.propertyIsEnumerable('toString')); //false; 不可枚举

    除了使用in运算符之外,另一种更为简便的方法是使用 ‘!==’ 判断一个属性是否是undefined;

let j = {x: 1}
console.log(j.x !== undefined); // true; j中有属性x
console.log(j.y !== undefined); // false; j中没有属性y
console.log(j.toString !== undefined); // true; o继承了toString属性

然而有一种场景只能使用in运算符而不能使用上述属性的方法。in可以区分不存在的属性和存在但值为undefined的值。例如下面的代码;

let i = {x: undefined}
console.log(i.x !== undefined); //false; 属性存在,但值为undefined;
console.log(i.y !== undefined); // false; 属性不存在
console.log('x' in j); // true; 属性存在
console.log('y' in j); // false; 属性不存在
delete j.x; // 删除属性x
console.log('x' in j); // false; 属性不存在

注意,上述代码中使用的是‘!==’ 运算符,而不是 ‘!=’。 '!=='可以区分undefined和null。有时则不必作这种区分;

// 如果j中含有属性x,且x的值不是null或undefined,j.x乘以2.
if (j.x != null) j.x *= 2;
// 如果j中含有属性x,且x的值不能转换为false, j.x乘以2.
// 如果x是undefined、null、false、''、0或NAN, 则他保持不变
if (j.x) j.x *= 2

猜你喜欢

转载自blog.csdn.net/weixin_41111068/article/details/83547941