逍遥狂儒
采纳率:58% 擅长: JavaScript Html/Css
第一种,判断js对象中是否有某个属性
1 2 3 4 5 6 var obj = {test : 'test' }; if ( 'test' in obj){ console.log( 'yes' ); } else { console.log( 'no' ); }
第二种,判断js对象本身是否有某个属性(所谓本身有意思是,必须属性是直接在对象上的,而不是通过原型链上找到的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 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来判断在自身有没有。 cainiaokan | 发布于2015-01-23 17:28 评论 8