Is there a standard function to check for null, undefined, or blank variables in JavaScript?

前端 未结 30 3692
眼角桃花
眼角桃花 2020-11-21 23:37

Is there a universal JavaScript function that checks that a variable has a value and ensures that it\'s not undefined or null? I\'ve got this code,

30条回答
  •  [愿得一人]
    2020-11-22 00:03

    This will check if variable of indeterminate nesting is undefined

    function Undef(str) 
    {
      var ary = str.split('.');
      var w = window;
      for (i in ary) {
        try      { if (typeof(w = w[ary[i]]) === "undefined") return true; }
        catch(e) { return true; }
      }
      return false;
    }
    
    if (!Undef("google.translate.TranslateElement")) {
    

    The above checks if the Google translate function TranslateElement exists. This is equivalent to:

    if (!(typeof google === "undefined" 
     || typeof google.translate === "undefined" 
     || typeof google.translate.TranslateElement === "undefined")) {
    

提交回复
热议问题