我的javascript循环/ while语句代码不起作用,请帮助我确定我的问题

时间:2019-06-04 19:42:54

标签: javascript

显然,根据我的老师,我需要完善我的语法和逻辑。这没有任何意义(我的代码和对整个JavaScript的想法)

var die = Math.random() * 6;        // generate a random number

die = Math.ceil( die );     // round it to between 1 and 6

var counter = 1;

var x = prompt( "What is your first guess?"); // fill x variable with the guess.  Then compare the value in die to the value in x.  What would that code be?


        while (counter < 3)
        if (x==die)
        {alert "Well done you win!"}
        break;
        }
        else {
        prompt ("Sorry.  Not the right answer.  Try again");
        counter == counter+1;
        }

var counter = counter+1;

var y = prompt("What is your second guess?"); // second x value

        while (counter ==2)
        if (y==die)
        {alert "Well done"}
        break;
        }
        else{
        prompt ("Sorry, you were wrong. Last try.");
        counter == counter+1;
        }

var counter = counter+1;


        var z = prompt("What is your third guess?"); // third x value

        while (counter == 3)
        if (z==die)
        {alert "Well done"}
        break;
        }
        else{
        prompt ("Sorry, you lost.");
        break;
        }

1 个答案:

答案 0 :(得分:1)

错误可能在该行中

counter == counter+1;

它应该是一个赋值表达式

counter = counter + 1;

使用while循环

一种好的方法是将字符串存储在数组中,然后在单个while循环中使用它们。

let arr = ["first","second","third"];
let die = Math.ceil(Math.random() * 6);
console.log(die);
let counter = 0;
while(counter < 3){
  let input = prompt("What is your " + arr[counter] + " guess?");
  if(+input === die){ // +input converts input into a number here
    alert("You win");
    break;
  }
  else{
    alert("Sorry try again");
  }
  counter++;
}

使用for循环

我会使用for循环来做到这一点。因为counter变量每次都增加一。

let arr = ["first","second","third"];
let die = Math.ceil(Math.random() * 6);
console.log(die);

for(let i = 0;i<3;i++){
  let input = prompt("What is your " + arr[i] + " guess?");
  if(+input === die){ // +input converts input into a number here
    alert("You win");
    break;
  }
  alert("Sorry try again");
}

使用for..of

我们已经有一个长度为3 ["first","second","third"]的数组。因此,我们不需要为循环创建变量然后使用它。我们可以使用for..of清理代码。我还使用模板字符串来寻求完美的解决方案

let arr = ["first","second","third"];
let die = Math.ceil(Math.random() * 6);
console.log(die);

for(let x of arr){
  let input = prompt(`What is your ${x} guess?`);
  if(+input === die){ // +input converts input into a number here
    alert("You win");
    break;
  }
  alert("Sorry try again");
}