How can I check JavaScript arrays for empty strings?

前端 未结 16 2032
面向向阳花
面向向阳花 2020-12-15 07:26

I need to check if array contains at least one empty elements. If any of the one element is empty then it will return false.

Example:

var my_arr = ne         


        
相关标签:
16条回答
  • 2020-12-15 07:59
    var containsEmpty = !my_arr.some(function(e){return (!e || 0 === e.length);});
    

    This checks for 0, false, undefined, "" and NaN. It's also a one liner and works for IE 9 and greater.

    0 讨论(0)
  • 2020-12-15 08:00

    I don't know if this is the most performant way, but here's a one liner in ES2015+:

    // true if not empty strings
    // false if there are empty strings
    my_arr.filter(x => x).length === my_arr.length
    

    The .filter(x => x) will return all the elements of the array that are not empty nor undefined. You then compare the length of the original array. If they are different, that means that the array contains empty strings.

    0 讨论(0)
  • 2020-12-15 08:02
    yourArray.join('').length > 0
    

    Join your array without any space in between and check for its length. If the length, turns out to be greater than zero that means array was not empty. If length is less than or equal to zero, then array was empty.

    0 讨论(0)
  • 2020-12-15 08:03

    You can try jQuery.inArray() function:

    return jQuery.inArray("", my_arr)
    
    0 讨论(0)
  • 2020-12-15 08:03

    Just do a len(my_arr[i]) == 0; inside a loop to check if string is empty or not.

    0 讨论(0)
  • 2020-12-15 08:05

    I see in your comments beneath the question that the code example you give is PHP, so I was wondering if you were actually going for the PHP one? In PHP it would be:

    function hasEmpty($array)
    {
      foreach($array as $bit)
      {
        if(empty($bit)) return true;
      }
    
      return false;
    }
    

    Otherwise if you actually did need JavaScript, I refer to Nick Craver's answer

    0 讨论(0)
提交回复
热议问题