Checking something isEmpty in Javascript?

后端 未结 18 2508
天涯浪人
天涯浪人 2020-12-12 12:38

How can I check if a variable is empty in Javascript? Sorry for the stupid question, but I\'m a newbie in Javascript!

if(response.photo) is empty {
    do so         


        
18条回答
  •  伪装坚强ぢ
    2020-12-12 13:06

    Here's a simpler(short) solution to check for empty variables. This function checks if a variable is empty. The variable provided may contain mixed values (null, undefined, array, object, string, integer, function).

    function empty(mixed_var) {
     if (!mixed_var || mixed_var == '0') {
      return true;
     }
     if (typeof mixed_var == 'object') {
      for (var k in mixed_var) {
       return false;
      }
      return true;
     }
     return false;
    }
    
    //   example 1: empty(null);
    //   returns 1: true
    
    //   example 2: empty(undefined);
    //   returns 2: true
    
    //   example 3: empty([]);
    //   returns 3: true
    
    //   example 4: empty({});
    //   returns 4: true
    
    //   example 5: empty(0);
    //   returns 5: true
    
    //   example 6: empty('0');
    //   returns 6: true
    
    //   example 7: empty(function(){});
    //   returns 7: false
    

提交回复
热议问题