js判断对象属性是否存在的三种方法

1.in 可以检测自有属性和继承属性

var o={x:1}
'x' in o  //返回true
'y'in o //返回false
'toString' in o //返回true,因为对象o继承了原型的toString属性

2.hasOwnProperty() 只能检测自有属性

var o={x:1};
o.hasOwnProperty('x')  //返回true
o.hasOwnProperty('y')  //返回false
o.hasOwnProperty('toString') //返回false,因为对象o继承的原型的toString属性

3.使用!==检测

var o={x:1}
o.x !== undefined  //返回true
o.y !== undefined //返回false
o.toString !== undefined //返回true,因为对象o继承了原型的toString属性

使用!需要注意对象的属性值不能设置为undefined
注意必须是!
,而不是!= 因为!=不区分undefined和null

var o={x:undefined  }
o.x !== undefined  //返回false
o.y !== undefined //返回false

参考javascript权威指南第6版

你可能感兴趣的:(js)