简体   繁体   中英

Why is this do/while loop crashing?

var doLoop = ("This is a do loop ya'll");    
var doLoopArray = [];    
var doLoopCount = 1; 

do (console.log(doLoop)); 
while(doLoopCount <= doLoop.length); {
     console.log(doLoop(0, doLoopCount));
     doLoopCount += 1;
}

I thought this do loop would run 23 times (number of characters in the doLoop string and then stop, but it seems to be infinite.

The problem is that you have the code body after the while . That's not where it goes with a [ do-while 2 ! The code is supposed to go in the do block.

Your code is being parsed as:

do{
    (console.log(doLoop));
}
while(doLoopCount <= doLoop.length);
{
     console.log(doLoop(0, doLoopCount));
     doLoopCount += 1;
}

This is why it is an infinite loop. It sees the code in the {} as a block , and not part of the do-while structure.

You need to structure the do-while correctly. It should probably be:

do{
    console.log(doLoop);
    console.log(doLoop(0, doLoopCount));
    doLoopCount += 1;
} while(doLoopCount <= doLoop.length);

PS doLoop(0, doLoopCount) is not going to work. doLoop is a string, not a function.

do syntax is:

  1. do
  2. statement or block
  3. while condition

You have your while condition immediately following the do and then you have the block.

It should be:

do {
    console.log(doLoop); 
    // You also need to fix this line. `doLoop` is a string, so you can't call it
    // as a function, but I'm not sure what you are trying to do here.
    console.log(doLoop(0, doLoopCount));
    doLoopCount += 1;
} while(doLoopCount <= doLoop.length);

Here is your code, with intuitive indenting.

var doLoop = ("This is a do loop ya'll");    
var doLoopArray = [];    
var doLoopCount = 1; 

do ({
  // You never increment doLoopCount in the body of the loop
  console.log(doLoop);
} while(doLoopCount <= doLoop.length);

// This is a separate block that is not part of the loop.
{
  // doLoop is not a function.
  console.log(doLoop(0, doLoopCount));
  doLoopCount += 1;
}

Your loop will run infinitely, and never reach the illegal call at the end.

What you probably meant was something like

var doLoopCount = 1; 
console.log(doLoop);
while (doLoopCount < doLoop.length) {
  console.log(doLoop[doLoopCount]);
  doLoopCount += 1;
}

or better yet

console.log(doLoop);
for (var doLoopCount = 0; doLoopCount < doLoop.length; ++doLoopCount) {
  console.log(doLoop[doLoopCount]);
}

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