js检测对象中是否存在某个属性

var o={x:1};
"x" in o; //true,自有属性存在
"y" in o; //false
"toString" in o; //true,是一个继承属性

使用对象的hasOwnProperty()方法

该方法只能判断自有属性是否存在,对于继承属性会返回false。

var o={x:1};
o.hasOwnProperty("x");    //true,自有属性中有x
o.hasOwnProperty("y");    //false,自有属性中不存在y
o.hasOwnProperty("toString"); //false,这是一个继承属性,但不是自有属性

 

posted @ 2019-02-25 14:07  Webwhl  阅读(4478)  评论(0编辑  收藏  举报