How to make a function to tell when an array is empty?

Asked

Viewed 819 times

5

I need a function that lets me know when an array is empty,

function validaCampo(){    
   if(count(dias[])==0)
        {
        alert("O Campo Dias disponíveis é obrigatório!");
        return false;
        }
      else
      return true;
}
  • 1

    It is not enough just to check the length of the array?

  • Hello Already tried to get lenth if(days.length <= 1) { Alert("The Available Days Field is required!"); Return false; }

  • True, I was thinking that the command that brought the size of an array was Count, thank you very much!!!

4 answers

11


Javascript does not have count(), this is PHP. You can use .length thus:

if(dias.length == 0){
    // etc
}

If you only want a Boolean, you can do it like this:

function validaCampo() {
  const valido = dias.length > 0;
  if (!valido) alert("O Campo Dias disponíveis é obrigatório!");
  return valido;

}

3

function checkArray(arr) {
  return !!arr.length
}

3

3

Check the length array.

vetor = [];
vetor1 = ['item1'];

validaVetor(vetor);
validaVetor(vetor1);

function validaVetor(vetor){
  if(vetor.length>0){
    console.log("Vetor populado");
  }else{
    console.log("Vetor vazio");
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  • It worked that way, thank you very much!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.