How can I check JavaScript arrays for empty strings?

前端 未结 16 2033
面向向阳花
面向向阳花 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 08:06

    You can check by looping through the array with a simple for, like this:

    function NoneEmpty(arr) {
      for(var i=0; i<arr.length; i++) {
        if(arr[i] === "") return false;
      }
      return true;
    }
    

    You can give it a try here, the reason we're not using .indexOf() here is lack of support in IE, otherwise it'd be even simpler like this:

    function NoneEmpty(arr) {
      return arr.indexOf("") === -1;
    }
    

    But alas, IE doesn't support this function on arrays, at least not yet.

    0 讨论(0)
  • For Single dimensional Array

    array.some(Boolean)
    

    For Multi dimensional Array

    array.some(row => row.some(Boolean))
    
    0 讨论(0)
  • 2020-12-15 08:13
    my_arr.includes("")
    

    This returned undefined instead of a boolean value so here's an alternative.

    function checkEmptyString(item){
         if (item.trim().length > 0) return false;
         else return true;
        };
        
    function checkIfArrayContainsEmptyString(array) {
      const containsEmptyString = array.some(checkEmptyString);
      return containsEmptyString;
    };
        
    console.log(checkIfArrayContainsEmptyString(["","hey","","this","is","my","solution"]))
    // *returns true*
    
    console.log(checkIfArrayContainsEmptyString(["yay","it","works"]))
    // *returns false*

    0 讨论(0)
  • 2020-12-15 08:16
    function containsEmpty(a) {
        return [].concat(a).sort().reverse().pop() === "";
    }
    alert(containsEmpty(['1','','qwerty','100'])); // true
    alert(containsEmpty(['1','2','qwerty','100'])); // false
    
    0 讨论(0)
  • 2020-12-15 08:17

    You have to check in through loop.

    function checkArray(my_arr){
       for(var i=0;i<my_arr.length;i++){
           if(my_arr[i] === "")   
              return false;
       }
       return true;
    }
    
    0 讨论(0)
  • 2020-12-15 08:17

    Nowadays we can use Array.includes

    my_arr.includes("")
    

    Returns a Boolean

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