Checking something isEmpty in Javascript?

后端 未结 18 2509
天涯浪人
天涯浪人 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 12:48

    This is a bigger question than you think. Variables can empty in a lot of ways. Kinda depends on what you need to know.

    // quick and dirty will be true for '', null, undefined, 0, NaN and false.
    if (!x) 
    
    // test for null OR undefined
    if (x == null)  
    
    // test for undefined OR null 
    if (x == undefined) 
    
    // test for undefined
    if (x === undefined) 
    // or safer test for undefined since the variable undefined can be set causing tests against it to fail.
    if (typeof x == 'undefined') 
    
    // test for empty string
    if (x === '') 
    
    // if you know its an array
    if (x.length == 0)  
    // or
    if (!x.length)
    
    // BONUS test for empty object
    var empty = true, fld;
    for (fld in x) {
      empty = false;
      break;
    }
    

提交回复
热议问题