How can I check JavaScript arrays for empty strings?

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

    Using a "higher order function" like filter instead of looping can sometimes make for faster, safer, and more readable code. Here, you could filter the array to remove items that are not the empty string, then check the length of the resultant array.

    Basic JavaScript

    var my_arr = ["", "hi", ""]
    
    // only keep items that are the empty string
    new_arr = my_arr.filter(function(item) {
      return item === ""
    })
    
    // if filtered array is not empty, there are empty strings
    console.log(new_arr);
    console.log(new_arr.length === 0);

    Modern Javascript: One-liner

    var my_arr = ["", "hi", ""]
    var result = my_arr.filter(item => item === "").length === 0
    console.log(result);

    A note about performance

    Looping is likely faster in this case, since you can stop looping as soon as you find an empty string. I might still choose to use filter for code succinctness and readability, but either strategy is defensible.

    If you needed to loop over all the elements in the array, however-- perhaps to check if every item is the empty string-- filter would likely be much faster than a for loop!

提交回复
热议问题