Can I use = for the condition in for loops?

时间:2019-04-17 00:56:19

标签: arrays

I am trying to make a program on a website that helps you learn coding (codehs) I am trying to make a program that adds one until it equals the actual passcode. I am a newbie, so I may be doing things wrong, but I don't want it to continue until it is less than my variable. I want to do it until it equals it.

I'm just unsure if this will work.

function start() {
    var secretPasscode = generateRandomPasscode();
    var count = 0;
    var guessed = 0000;
    for(i = 0; i = secretpasscode; i++){
      guessed += 1;  
      count++;
    } 
}

Will it work like this? I want it to continue until it equals that variable.

1 个答案:

答案 0 :(得分:0)

assuming you are using JS for this.

function start() {
  var secretPasscode = generateRandomPasscode();
  var guessed;
  for(guessed = 0; guessed != secretpasscode; guessed ++);

  console.log(guessed);

}

You get your random number from the function generateRandomPasscode. You define your guessedvariable outside the for loop so that we can access it later on. Started counting from 0 because you want to know actual number of how many times the loop iterated. Using console.log(guessed) you can check the number of iterations it took to reach the answer.

On the other hand you can do this which will give you the same answer :

function start() {
  console.log(generateRandomPasscode());
}

Because the loop that you are trying to make will always be equal to the number that is returned by your generateRandomPasscode()