Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip to next in javascript in a for-in with a while inside?

I have a short javascript code where I need to skip to next in the for loop....see below:

var y = new Array ('1', '2', '3', '4'); for (var x in y) {    callFunctionOne(y[x]);    while (condition){        condition = callFunctionTwo(y[x]);        //now want to move to the next item so         // invoke callFunctionTwo() again...    } } 

Wanted to keep it simple so syntax may be error free.

like image 864
Ram Iyer Avatar asked Feb 22 '13 23:02

Ram Iyer


People also ask

How do you skip to the next element in a for loop?

The continue statement in Python is used to skip the rest of the code inside a loop for the current iteration only. In other words, the loop will not terminate immediately but it will continue on with the next iteration. This is in contrast with the break statement which will terminate the loop completely.

How do you skip to next iteration in a while loop?

You can use the continue statement if you need to skip the current iteration of a for or while loop and move onto the next iteration.

How do you skip a while loop in JavaScript?

The continue statement (with or without a label reference) can only be used to skip one loop iteration. The break statement, without a label reference, can only be used to jump out of a loop or a switch.

Is there a continue in JavaScript?

The continue statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.


1 Answers

Don't iterate over arrays using for...in. That syntax is for iterating over the properties of an object, which isn't what you're after.

As for your actual question, you can use the continue:

var y = [1, 2, 3, 4];  for (var i = 0; i < y.length; i++) {     if (y[i] == 2) {         continue;     }      console.log(y[i]); } 

This will print:

1 3 4 

Actually, it looks like you want to break out of the while loop. You can use break for that:

while (condition){     condition = callFunctionTwo(y[x]);     break; } 

Take a look at do...while loops as well.

like image 148
Blender Avatar answered Oct 11 '22 21:10

Blender