JavaScript Required
We’re sorry, but Coda doesn’t work properly without JavaScript enabled.
Skip to content
Loops en JavaScript
1. What is a Loop?
2. while Loop
3. do while Loop
4. Add One to a Number with the Increment Operator (++)
5. Challenge Loop
6. Bewere of Infinite Loops!
7. Evaluación Loops
8. for loop
9. Dynamically Display HTML with a Loop
10. Exit a Loop
11. The refactor Challenge
12. Challenge Task
More
Share
Explore
2. while Loop
Use the
while
statement to create a loop that executes code as long as a condition evaluates to true.
Estructura de un
while
Mientras la condición
( )
sea verdadera, se ejecutará el scope
{ }
en un loop.
Ejemplo
En el archivo
while.js
function getRandomNumber(upper) {
return Math.floor( Math.random() * upper ) + 1;
}
Si quisiéramos ejecutar esa función 10 veces deberíamos hacer algo como:
getRandomNumber(200);
getRandomNumber(200);
getRandomNumber(200);
getRandomNumber(200);
getRandomNumber(200);
getRandomNumber(200);
getRandomNumber(200);
getRandomNumber(200);
getRandomNumber(200);
getRandomNumber(200);
Lo anterior podemos reescribirlo como un loop
function getRandomNumber(upper) {
return Math.floor( Math.random() * upper ) + 1;
}
let counter = 0; // Creamos un contador que inicia en 0
while ( counter < 10 ) {
console.log(`El número aleatorio es: ${getRandomNumber(200)}`)
counter += 1; // sumamos 1 al contador
}
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
Ctrl
P
) instead.