ingrese la descripción de la imagen aquí Esta es mi imagen de salida:
function bottles_of_beer(){ var i=99; while(i>=0){ if(i==1){ console.log(i+" bottles of beer on the wall, "+i+" bottles of beer.\nTake one down and pass it around, No more bottles of beer on the wall."); } else if(i==0){ console.log("No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall."); } else{ console.log(i+" bottles of beer on the wall, "+i+" bottles of beer.\nTake one down and pass it around, "+i-1+" bottles of beer on the wall.") } i--; } }Esperaba la salida impresa en la consola 100 veces. Pero solo está imprimiendo la salida para i = 1 e i = 0 y para i: 99 a 2 solo está imprimiendo una salida. ¿Por qué está sucediendo esto alguien puede explicar por favor? y ¿cómo puedo mostrar/imprimir la salida 100 veces en la consola?
Este es el resultado que obtengo cuando llamo "bottles_of_beer()":
Botellas de cerveza de 98 NaN en la pared.
1 botellas de cerveza en la pared, 1 botellas de cerveza. Tome uno y páselo. No más botellas de cerveza en la pared.
No más botellas de cerveza en la pared, no más botellas de cerveza. Ve a la tienda y compra más, 99 botellas de cerveza en la pared.
En su último registro de consola:
console.log( i + " bottles of beer on the wall, " + i + " bottles of beer.\nTake one down and pass it around, " + i - 1 + " bottles of beer on the wall." ); Todo antes del -1 está bien como una cadena, pero cuando tienes some_string - 1 JS intenta convertir la cadena en un número y luego restar 1. Es por eso que obtienes NaN.
Para resolverlo, simplemente envuelva su i - 1 en el último registro de la consola entre paréntesis
console.log( i + " bottles of beer on the wall, " + i + " bottles of beer.\nTake one down and pass it around, " + (i - 1) + " bottles of beer on the wall." );Hay dos formas de resolver esto
1. Puede colocar , en lugar de + antes de i-1
console.log( i + " bottles of beer on the wall, " + i + " bottles of beer.\nTake one down and pass it around, ", i - 1 + " bottles of beer on the wall." ); }2. Puedes envolver entre paréntesis
(i-1)