简体   繁体   中英

Javascript loop stuck

When I am running this script it gets stuck on prompting the user for the first number. It seems to not be counting up x.

function doMath() {
    for (var x = 1; x < 3; x = x + 1) {
        var var1;
        var var2;
        var var2;
        var num;
        if (x = 1) {
            var num = prompt("Enter first number please");
            var1 = parseInt(num)
        }
        else if (x = 2) {
            var num = prompt("Enter second number please");
            var2 = parseInt(num)
        }
        else {
            var num = prompt("Enter third number please");
            var3 = parseInt(num)
            return Math.min(var1, var2, var3);
        }
    }
}

See line:

if (x = 1)

You are not checking if x == 1 but instead are making an assignment x=1. The latter is always true which means the condition is always met and that is why your code keeps prompting the user. Similarly for the other conditionals. They are all assignments. Hope this helps!

There are a few issues with your code:
- In your for-loop x would only ever be 1 or 2 seeing that : ( x < 3 ) which mean it would never return a result
- To check for equality in an if-statement you need == or === not = which is assignment
- You are re-declaring your variables every iteration of the loop, and thus losing any stored information
- return after the for-loop completes

Putting it all together:

function doMath() {
    var var1;
    var var2;
    var var2;
    var num;
    for(var x =1; x <= 3; x++){ //use x++ instead of x = x + 1 (easier to read) 
        if (x == 1) { //fix here
           var num = prompt("Enter first number please");
           var1 = parseInt(num)
        } else if (x == 2) { //and here
           var num = prompt("Enter second number please");
           var2 = parseInt(num)
        } else {
           var num = prompt("Enter third number please");
           var3 = parseInt(num) 
        }
    }

    return Math.min(var1, var2, var3);
}

You are not calling the function and not outputting the final result.

Here's a working solution. Hope it helps!

 function doMath() { var var1; var var2; var num; for(var x =1; x <= 3; x++){ //use x++ instead of x = x + 1 (easier to read) if (x == 1) { //fix here var num = prompt("Enter first number please"); var1 = parseInt(num) } else if (x == 2) { //and here var num = prompt("Enter second number please"); var2 = parseInt(num) } else { var num = prompt("Enter third number please"); var3 = parseInt(num) } } return Math.min(var1, var2, var3); } document.write(doMath()); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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