Wednesday, 12 October 2016

javascript - Break statement won't break the loop





I want to set the first least common multiple of 2 number(n1 and n2), but my break statement won't work. I don't want to use a return(which it works). Is there a way to work around this? Thanks.



var firstDayTogether,n1,n2;

for(var i=1;i<12345;i++){
for(var j=1;j<12345;j++){
if((s1*i)==(s2*j)){
firstDayTogether=(s1*i);
break;
}

}
}

Answer



You're only breaking out of the inner loop. You can use a label to specify which loop to end.



outerloop: for( var i=1; i<12345; i++) {
for( var j=1; j<12345; j++) {
if((s1*i)==(s2*j)) {
firstDayTogether = s1*i;

break outerloop; // <== !!
}
}
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...