Check if object exists in JavaScript

前端 未结 18 2693
抹茶落季
抹茶落季 2020-12-04 05:26

How do I verify the existence of an object in JavaScript?

The following works:

if (!null)
   alert(\"GOT HERE\");

But this throws a

18条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 05:45

    Apart from checking the existence of the object/variable you may want to provide a "worst case" output or at least trap it into an alert so it doesn't go unnoticed.

    Example of function that checks, provides alternative, and catch errors.

    function fillForm(obj) {
      try {
        var output;
        output = (typeof obj !== 'undefined') ? obj : '';
        return (output);
      } 
      catch (err) {
        // If an error was thrown, sent it as an alert
        // to help with debugging any problems
        alert(err.toString());
        // If the obj doesn't exist or it's empty 
        // I want to fill the form with ""
        return ('');
      } // catch End
    } // fillForm End
    

    I created this also because the object I was passing to it could be x , x.m , x.m[z] and typeof x.m[z] would fail with an error if x.m did not exist.

    I hope it helps. (BTW, I am novice with JS)

提交回复
热议问题