如题所述
第一种,判断js对象中是否有某个属性
var obj = {test : 'test'};if('test' in obj){
console.log('yes');
} else {
console.log('no');
}
第二种,判断js对象本身是否有某个属性(所谓本身有意思是,必须属性是直接在对象上的,而不是通过原型链上找到的。
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);
}本回答被提问者和网友采纳
举例
"name" in Object
Object.hasOwnProperty("name")
有个公共的方法
function hasPrototype(object,name){
return !object.hasOwnProperty(name)&&(name in object);
}本回答被提问者和网友采纳