Array counter with while in JS

0

I need to count the elements of an array using the while loop and display a alert() , but it is not displaying the count in the browser . Using for worked fine.

I leave my code below:

var deuses = new Array();
  deuses = ['aegir', 'aud', 'balder'];

  var i = 0;

   while (i < deuses){
        alert(deuses.length);
   i++;
}
    
asked by anonymous 25.07.2018 / 15:24

1 answer

1

What you want is not to count the items, even because it's complicated to tell something without knowing how many have, and knowing how many do not have to count.

To tell something you do not know how many there are only if you have a clear terminator, which is not the case for a JavaScript array .

The statement asks you to do some of the simplest things with the array that is sweeping all of it with a loop. In fact there is no way to do otherwise. You can even use a function that abstracts this, but in practice it will have a loop inside it.

See documentation for how for - of whose function is to just walk element by element and give a variable for you to do what you want with it during the execution of that step. This form is quick and secure, and very simple.

Exercise does not ask you to do something complex.

for (var item of ['aegir', 'aud', 'balder']) alert(item);

If you want to do good manual it could look like this:

var deuses = ['aegir', 'aud', 'balder'];
var i = 0;
while (i < deuses.length) { //vai até o tamanho já conhecido
   alert(deuses[i]); //pega o elemento indexado pela variável de controle do laço
   i++; //incrementa a variável para o próximo passo
}

But you take risks. This is a case that seems obvious, but I see a lot of people making mistakes even in something simple like that, especially going beyond size.

    
25.07.2018 / 16:02