首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何访问while循环中的变量?

如何访问while循环中的变量?
EN

Stack Overflow用户
提问于 2022-05-03 05:12:05
回答 1查看 226关注 0票数 0

我正在尝试访问第二个while循环中的问题2,但我不能访问,因为它位于第一个while循环中的块范围中。我厌倦了在while循环之外声明它,但是while循环将无法工作。任何帮助都是非常感谢的。第二个while循环中的if语句将无法工作,因为问题2位于块作用域中。

代码语言:javascript
运行
复制
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();

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72095016

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档