简体   繁体   中英

Print hello twice via Javascript

I am supposed to make this echo "hello" twice while only changing two things: fix the iterator so it increments each time, and set the while loop so it only runs twice. I'm a beginner so I'm not sure how to do this, really. Any suggestions?

var times = 0;
while ( ) {
  console.log( "hello" );
  times
};

while is a loop that takes an expression. While the expression is truthy (true for all intents and purposes), it will execute the code in the following statement or block.

So, how would you keep a counter for a loop? You want the counter to start at zero and go up to 2, then, once it reaches 2, it should stop. Suffice to say, you want to loop while your counter is less than 2, that is, < 2 . So your expression is:

times < 2

and your loop is therefore:

while(times < 2) {

Now, you'll also need to increment your times variable so it goes up each time around the loop. There are a couple ways to do this. A nice and clear one should be:

times = times + 1;

But people usually contract it to times += 1; , or for incrementing by one:

times++;

So, your loop should end up as:

while(times < 2) {
    console.log("hello");
    times++;
}

The while loop's condition will check if times is less than 2. If it is, print hello and increment times .

var times = 0;
while (times < 2) { // 'times < 2' is the condition, what gets checked each iteration
  console.log( "hello" );
  times++; // set 'times' to 'times + 1'
};

Here's another way it could work

var times = 0;
while (times != 2) {
    console.log( "hello" );
    times = times + 1;
};

Computer scientists are anathema to this because times != 2 is not tight enough for them. They claim times < 2 is better. Although correct, this way makes more sense to non programmers because you are essentially saying "once you hit 2 stop!". Also times++ is a shorthand version for times = times + 1

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