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

    xiaoxiao2021-12-14  20

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

    Crazy_gsuz  |  浏览 7713 次 发布于2015-01-23 17:29 最佳答案 可以用 in操作符 和 对象的 hasOwnProperty 操作符 举例 "name" in Object Object.hasOwnProperty("name") 有个公共的方法 function hasPrototype(object,name){ return !object.hasOwnProperty(name)&&(name in object); }  本回答由提问者推荐 评论(2)  8  1

    逍遥狂儒 

    采纳率: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 
    转载请注明原文地址: https://ju.6miu.com/read-962709.html

    最新回复(0)