Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

176
Vistas
¿Cómo accedo a una variable dentro de un ciclo while?

Estoy tratando de acceder a la pregunta 2 en el segundo ciclo while, pero no puedo porque está en un alcance de bloque en el primer ciclo while. Me cansé de declararlo fuera del ciclo while pero entonces el ciclo while no funcionará. Cualquier ayuda es apreciada. La declaración if en el segundo ciclo while no funcionará porque la pregunta 2 está en un alcance de bloque.

 var readlineSync = require("readline-sync"); function run() { var question1 = readlineSync.question("Press any key to start the game"); const randomNumber1 = Math.floor(Math.random() * 3) + 1; const randomNumber2 = Math.floor(Math.random() * 3) + 1; /*first placement*/ firststring(1); function firststring(stringlength) { var emptyString1 = ""; var emptyString2 = ""; var characters = "ABC"; var characters2 = "ABC"; let operation1 = false; let operation2 = false; for (var i, i = 0; i < stringlength; i++) { emptyString1 += characters.charAt( Math.floor(Math.random() * characters.length) ); } for (var i, i = 0; i < stringlength; i++) { emptyString2 += characters.charAt( Math.floor(Math.random() * characters2.length) ); } var totalOne = emptyString1 + randomNumber1; var totalTwo = emptyString2 + randomNumber2; var toString1 = totalOne.toString(); var toString2 = totalTwo.toString(); console.log(toString1); console.log(toString2); if (toString1 === toString2 || totalOne === totalTwo) { run(); } let question2; while (!operation1) { question2 = readlineSync.question('Enter a location to strike ie "A2"'); if (question2 === toString1 || question2 === toString2) { operation1 = true; console.log("Hit. You have sunk a battleship. 1 ship remaining."); break; } else { console.log("You have missed!"); } } let question3; let question4; while (!operation2) { question3 = readlineSync.question("Enter a location to strike the second battleship") if (question3 === toString1 || question3 === toString2) { operation2= true; console.log('HIT!') break; } else { console.log('You have misssed') } if (question3 === question2) { console.log("You have already entered that value."); } } question4 = readlineSync.question( "You have destroyed all battleships. Would you like to play again? Y/N" ); if(question4 === "Y" || question4 === "y") { run(); } } } run();

ingrese la descripción de la imagen aquí

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

En el código anterior, question2 se declara y está disponible para toda la función firststring , y está disponible para ambos bucles while.

let en JavaScript define una variable para su alcance actual y cualquier cosa debajo de esta manera:

 let a; let b = 3; if (true) { console.log(b); // 3 let c = 5; b = 4; a = 6; } console.log(a); // 6 console.log(b); // 4 // console.log(c); // Uncaught ReferenceError: c is not defined

EDITAR: con el resultado del ejemplo proporcionado, el problema es que la verificación if (question3 === question2) se llama después de la "verificación de éxito" (que rompe el ciclo). Necesitas esto:

 while (!operation2) { question3 = readlineSync.question("Enter a location to strike the second battleship") if (question3 === question2) { console.log("You have already entered that value."); } else if (question3 === toString1 || question3 === toString2) { operation2= true; console.log('HIT!') break; } else { console.log('You have misssed') } }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda