判断JS对象是否拥有某属性

如题所述

第一种,判断js对象中是否有某个属性

var obj = {test : 'test'};
if('test' in obj){
    console.log('yes');
} else {
    console.log('no');
}


第二种,判断js对象本身是否有某个属性(所谓本身有意思是,必须属性是直接在对象上的,而不是通过原型链上找到的。

var Base = function(){};
Base.prototype.test = 'test';

var obj = new Base();
obj.test2 = 'test2';

if('test1' in obj){
    console.log('yes');
} else {
    console.log('no');
}

if(obj.hasOwnProperty('test2')){
    console.log('own');
} else {
    console.log('none');
}

//用in 操作符,可以判断有没有。 用hasOwnProperty来判断在自身有没有。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-02-02
可以用 in操作符 和 对象的 hasOwnProperty 操作符

举例

"name" in Object

Object.hasOwnProperty("name")

有个公共的方法

function hasPrototype(object,name){
return !object.hasOwnProperty(name)&&(name in object);
}本回答被提问者和网友采纳

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网