简体   繁体   English

For循环不会在每次迭代时停止

[英]For loop not stopping at each iteration

I am a beginner to JavaScript, writing a hangman-type game where a user enters a string answer, then enters one character at a time to try and guess the answer. 我是JavaScript的初学者,写了一个子手式游戏,用户输入一个字符串答案,然后一次输入一个字符来尝试猜测答案。 (I'm changing it later to use an array of set answers instead of a user entered one, this way is just for testing). (我稍后将其更改为使用一组设置的答案,而不是用户输入的答案,这种方式仅用于测试)。 However, when I try to loop through my answer array and compare it to the input character in the function answerFunction(), it sets my whole blank array the same as the answer array instead of one character at a time as I want. 但是,当我尝试遍历答案数组并将其与功能answerFunction()中的输入字符进行比较时,它将整个空白数组设置为与答案数组相同,而不是一次设置一个字符。

<html>

<head>
    <script src="hangman.js"></script>
</head>

<body>
    <h2>Hangman Game</h2>
    <p>Game Description</p>
    <input id="userinput" placeholder="Input Answer"></input>
    <button value='send' id="submit" onclick="userInput()">Submit</button><br><br>
    <input id="userguess" placeholder="Input Guess"></input>
    <button value='send' id="submit" onclick="userGuess()">Submit</button>
    <p id="answer-placeholder"></p>
    <p id="guess-placeholder"></p>
</body>

</html>
function userInput() {
    inputAnswer = document.getElementById("userinput").value;
    answerArray = inputAnswer.split("");
    blankArray = answerArray.slice(0);
    blankArray.fill("_ ");
    document.getElementById("answer-placeholder").innerText = blankArray;
}

function userGuess() {
    inputChar = document.getElementById("userguess").value;
    answerLoop();
}

function answerLoop() {
    for (var i = 0; i < answerArray.length; i++) {
        if (inputChar = answerArray[i]) {
            blankArray[i] = answerArray[i];
            document.getElementById("guess-placeholder").innerText = blankArray;
        } else {
            break;
        }
    }
}

Example: Answer is John I type in J, and it displays J,o,h,n instead of the expected J, , ,_ 例如:应答是以J约翰I型,它显示J,N的O,H,而不是预期的J,K,_

There are two issues. 有两个问题。 Like, Marty said, you are trying to compare two values in your if statement. 就像Marty所说的那样,您正在尝试比较if语句中的两个值。 You need to use == instead of = . 您需要使用==而不是= When you use = in an if statement, the assignment operation will be performed instead of comparison. if语句中使用=时,将执行赋值操作而不是比较。 This is an easy mistake to make because JavaScript won't give you any kind of warning. 这是一个容易犯的错误,因为JavaScript不会给您任何警告。 It will simply evaluate the value that you assigned as true or false . 它只会评估您分配为truefalse

So what happens here? 那么这里发生了什么? The value at answerArray[i] is assigned to inputChar . answerArray[i]处的值分配给inputChar This will be a string containing 1 character. 这将是一个包含1个字符的字符串。 This value is then be evaluated. 然后评估该值。 The confusing thing is that JavaScript evaluates any string as true. 令人困惑的是,JavaScript将任何字符串评估为true。 These types of values are called a "truthy" value. 这些类型的值称为“真实”值。 So the code inside the if statement will actually be executed every time the for loop executes. 因此,每次for循环执行时, if语句中的代码实际上将被执行。 That's definitely not what you want. 那绝对不是你想要的。

The other problem is that you are using break in the else block. 另一个问题是您在else块中使用break You don't want to do that because it breaks the loop early if there is no match the first time the loop is executed. 您不希望这样做,因为如果第一次执行循环时没有匹配项,它将尽早中断循环。 In other words, on the first iteration. 换句话说,在第一次迭代中。 But remember that the user's guess might match the 2nd, 3rd, 4th, etc. letter. 但是请记住,用户的猜测可能与第二,第三,第四等字母匹配。 So basically get rid of the break as well. 因此基本上也摆脱了break

So the JS will look like this: 因此,JS将如下所示:

function userInput() {
    inputAnswer = document.getElementById("userinput").value;
    answerArray = inputAnswer.split("");
    blankArray = answerArray.slice(0);
    blankArray.fill("_ ");
    document.getElementById("answer-placeholder").innerText = blankArray;
  console.log(answerArray);
  console.log(blankArray);
}

function userGuess() {
    inputChar = document.getElementById("userguess").value;
    answerLoop();
}

function answerLoop() {
    for (var i = 0; i < answerArray.length; i++) {
        if (inputChar == answerArray[i]) {
            blankArray[i] = answerArray[i];
            document.getElementById("guess-placeholder").innerText = blankArray;

        } 
    }
}

That being said, you should also look into using the === operator instead of == . 话虽如此,您还应该研究使用===运算符而不是== This can help you avoid some annoying bugs in the future. 这可以帮助您避免将来出现一些烦人的错误。 In a nutshell, == will attempt to do type conversion for you. 简而言之, ==将尝试为您执行类型转换。 This means that it will return true in many cases where the two things you are comparing (the operands) are not of the same type. 这意味着在您要比较的两个事物(操作数)不是同一类型的许多情况下,它将返回true This answer gives a good summary of the differences between them: Which equals operator (== vs ===) should be used in JavaScript comparisons? 这个答案很好地总结了它们之间的区别: 在JavaScript比较中应使用哪个equals运算符(== vs ===)?

Also, here is some more info about break https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break 另外,这是有关break更多信息https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break

Use continue instead of break 使用continue而不是中断

break , stops the loop, continue well the name says it. break ,停止循环, continue就好了。 It continues the loop. 它继续循环。

You can see a reference here. 您可以在此处查看参考。 https://www.w3schools.com/js/js_break.asp https://www.w3schools.com/js/js_break.asp

Tbh You don't need even continue just dont use an else. Tbh您甚至不需要继续,只是不使用其他。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM