In Javascript. how can I tell if a field exists inside an object?

前端 未结 5 707
余生分开走
余生分开走 2021-01-31 07:12

And of course I want to do this code-wise. It\'s not that there isn\'t alternative to this problem I\'m facing, just curious.

5条回答
  •  醉梦人生
    2021-01-31 07:42

    After much frustration trying to test a field name which is passed via a variable, I came up with this:

    `function isset(fName){ 
        try{
            document.getElementById(fName).value=document.getElementById(fName).value;  
            return true;
        }catch(err){
            return false;
        }
     }
    

    `

    The function uses the try/catch function of javascript - if it can't set the field value it will trigger an error which is caught and passed back as false, otherwise true is returned.

提交回复
热议问题