How can I check JavaScript arrays for empty strings?

前端 未结 16 2052
面向向阳花
面向向阳花 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: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*

提交回复
热议问题