Skip to content Skip to sidebar Skip to footer

Alert An Array With While Loop

Using while loop, I want to alert names with their number from an array. I also have to put every name in a single alert. Script: var voetbalteam = 1; var spelers = ['Nobert Albl

Solution 1:

Use forEach() to loop over the array.

var voetbalteam = 1;

var spelers = ["Nobert Alblas", "Kostas Lamprou", "André Onana", "Benjamin van Leer", "Léon Bergsma", "Damil Dankerlui", "Matthijs de Ligt", "Mitchell Dijks", "Luis Orejuela", "Daley Sinkgraven", "Joël Veltman", "Nick Viergever", "Max Wöber", "Deyovaisio Zeefuik", "Frenkie de Jong", "Siem de Jong", "Carel Eiting", "Noussair Mazaoui", "Lasse Schöne", "Donny van de Beek", "Klaas Jan Huntelaar", "Kasper Dolberg", "Justin Kluivert"];

spelers.forEach(function(key, value){
  console.log("Ik ben " + key + " En ik ben de " + (value + 1) + "e speler.");
});

Using a while loop, use voetbalteam as an iterator and increment it inside the while loop.

var voetbalteam = 0;

    var spelers = ["Nobert Alblas", "Kostas Lamprou", "André Onana", "Benjamin van Leer", "Léon Bergsma", "Damil Dankerlui", "Matthijs de Ligt", "Mitchell Dijks", "Luis Orejuela", "Daley Sinkgraven", "Joël Veltman", "Nick Viergever", "Max Wöber", "Deyovaisio Zeefuik", "Frenkie de Jong", "Siem de Jong", "Carel Eiting", "Noussair Mazaoui", "Lasse Schöne", "Donny van de Beek", "Klaas Jan Huntelaar", "Kasper Dolberg", "Justin Kluivert"];


    while (voetbalteam < spelers.length){
        console.log("Ik ben " + spelers[voetbalteam] + " En ik ben de " + (voetbalteam + 1) + "e speler.");
        voetbalteam ++;
    }

consider using console.log() instead of alert() when you are coding.

  • alert() is blocking
  • alert() cannot be easily suppressed in non-debug environment
  • console typically formats your objects nicely and allows to traverse them
  • logging statements often have an interactive pointer to code which issued logging statement
  • you cannot look at more than one alert() message at a time
  • consoles can have different logging levels with intuitive formatting

The above text was taken from here

Solution 2:

If you really want to use a while loop, try this:

var voetbalteam = 0;

var spelers = ["Nobert Alblas", "Kostas Lamprou", "André Onana", "Benjamin van Leer", "Léon Bergsma", "Damil Dankerlui", "Matthijs de Ligt", "Mitchell Dijks", "Luis Orejuela", "Daley Sinkgraven", "Joël Veltman", "Nick Viergever", "Max Wöber", "Deyovaisio Zeefuik", "Frenkie de Jong", "Siem de Jong", "Carel Eiting", "Noussair Mazaoui", "Lasse Schöne", "Donny van de Beek", "Klaas Jan Huntelaar", "Kasper Dolberg", "Justin Kluivert"];

while (voetbalteam < spelers.length){
  alert("Ik ben " + spelers[voetbalteam] + " En ik ben de " + (voetbalteam + 1) + "e speler.");
  voetbalteam++;
}

Post a Comment for "Alert An Array With While Loop"