Not Able to Create Multiple Increments in One Loop Based on Conditions - javascript

Can you pleas etake a look at this demo and let me know why I am not able to create multiple increment in a loop
var i;
for (i = 0; i < 100;) {
console.log(i);
if (i < 50) {
i++;
}
if (i > 50) {
i += 2;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The problem with your code is that when i == 50, it doesn't get incremented, so it goes into an infinite loop. You need to change one of the conditions to include 50, e.g.
for (var i = 0; i < 100;) {
console.log(i);
if (i < 50) {
i++;
}
else if (i >= 50) {
i += 2;
}
}
Note that stack snippets crop the console output, so it appears to be starting at 25 when in fact it will start at 0.

Related

Is it possible to run a loop in segments? - JavaScript

Since I am still fairly new to js I thought it couldn't hurt to ask more experienced coders about ways to improve my coding habits and to learn efficient basics.
So im wondering if I could run, say 2 lines of code in a loop x amount of times and then x amount of times on the rest of the block.
So instead of this:
for (let i = 0; i <= 10; i++) {
this.shapes[i].x -= 1;
this.shapes[i].draw(this.ctx);
}
for (let i = 0; i <= 10; i++) {
this.shapes[i].x += 1;
this.shapes[i].draw(this.ctx);
}
Does something like this exist?
for (let i = 0; i <= 10; i++) {
//run this section i amount of times
this.shapes[i].x -= 1;
this.shapes[i].draw(this.ctx);
//then run this i amount of times
this.shapes[i].x += 1;
this.shapes[i].draw(this.ctx);
}
The only difference between the two loops' bodies seems to be one statement.
You can use some math to determine the index and some logical statements to determine if that value should be incremented or decremented, here is an example:
for (let i = 0; i <= 21; i++) {
const index = i % 11;
this.shapes[index].x += (i > 10) ? 1 : -1;
this.shapes[index].draw(this.ctx);
}
If it's exactly the same code you can refactor it like this:
for (let delta of [-1, +1]) {
for (let i = 0; i <= 10; i++) {
this.shapes[i].x += delta;
this.shapes[i].draw(this.ctx);
}
}
Another option is to use a function using delta as a parameter
changeShapeByDelta = (delta) => {
for (let i = 0; i <= 10; i++) {
this.shapes[i].x += delta;
this.shapes[i].draw(this.ctx);
}
}
changeShapeByDelta(-1);
changeShapeByDelta(+1);
Another option is to deep copy your initial shapes and restore it after the first draw.
You could ofc. define more variables then i:
for (let i = 0, j=0; i <= 10; i++, j+= 2) {
console.log(i, j);
}
Or use another var in the parent scope:
let j = 0;
for (let i = 0, j=0; i <= 10; i++, j+= 2) {
j += 2
console.log(i, j);
}
Or just use plain old if,else and break statements. Code does not have to look nice all the time.
You can loop 20 times instead of 10 times and then run first code if i<10 else run second. Below is example with simple logging.
for(let i = 0;i<22;i++){
if(i<11) console.log('first')
else console.log('second')
}

Java Script - Give certain array elements different colour

I am trying to do something with JS but as per usual arrays prove to be the bane of my existence...
I have to loop through the numbers from 1 to 100 and print them in the HTML, every number that divides by 3 should show in the colour red while all other numbers should be black. I tried so many things and tried to find how to do it but could not figure it out. Could anyone, please, tell me what is the proper way to do it?
You can use the following code to get what you are looking for.
for (let i = 1; i < 101; i++) {
if(i % 3 == 0) {
console.log('THREE');
} else {
console.log(i)
}
}
If you need to write the values to a document, change the console.log to document.write
Put the THREE in some inline element and add css rule to change the color.
For printing the list the solution explained by Jack. (Did it differently because I could.)
const text = (new Array(100))
.fill('')
.map((_v, i) => (i % 3) === 0 ? `<b>THREE</b>` : i)
.join('<br/>');
document.write(`<p>${text}</p>`)
b {
color: red;
}
First, loop through the numbers 1 to 100:
for (var i = 1; i <= 100; i++) {
//Stuff will go here
}
Then, write the number i to HTML:
document.write(i);
Finally, add the if statement:
if (i % 3) {
document.write(i);
} else {
document.write("THREE");
}
Full code:
for (var i = 1; i <= 100; i++) {
if (i % 3) {
document.write(i + "<br>");
} else {
document.write("THREE<br>");
}
}
EDIT
Here's how you'd make THREE red:
for (var i = 1; i <= 100; i++) {
if (i % 3) {
document.write(i + "<br>");
} else {
document.write("<span style='color: red;'>THREE</span><br>");
}
}

for loop is not stopping why? even I specifically say to stop on 10 in condition

for(var i = 0; i <= 10; i+1){
console.log(i); // the loop goes on and on
}
why this for loop don't stop ? I did specifically typed in condition that it need to stop on 10.
The i+1 is your issue. It should be i = i + 1, i++ or i+=1
These are just different ways of adding 1 to the current value of i
for(var i = 0; i <= 10; i++){
console.log(i);
}
You never change i.
for (var i = 0; i <= 10; i + 1) {
^^^^^
You need to increment i
for (var i = 0; i <= 10; i++) { // or
for (var i = 0; i <= 10; i = i + 1) {
It's missing the =: i is not being mutated:
for(var i = 0; i <= 10; i += 1){
console.log(i); // the loop goes on and on
}
Change it to i++ and it will work. Right now you are just checking against 0+1 every loop iteration, and that will never be > 10.

How to use continue in a loop to change a value

I am trying to have a loop that gives me values from 1 to 30. However every number divisible by 10 I want to hard code the value to the corresponding word. Example would be value 10 = "Ten", 20 = "Twenty" and so on.
I tried to do this with 'continue', however my displayed results do not go pass "Ten".
for (i = 0; i <= 30; i++) {
if (i == 10) {
i = "Ten";
continue;
} if (i == 20) {
i = "Twenty";
continue;
}
console.log(i);
}
Results
Am I going on about it the right way? Could you please offer some hints so I can figure this out. Thank you,
I tried this initially. But didn't work.
for (i = 0; i <= 30; i++) {
if (i == 10) {
i = "Ten";
} if (i == 20) {
i = "Twenty";
}
console.log(i);
}
Just get rid of the continue statements. They cause the loop to immediately skip to the end and start another iteration. Thus, your console output statement is skipped. Also, you don't want to touch the loop variable, and it wouldn't hurt to have an else. Something like this:
var result;
for (i = 0; i <= 30; i++) {
if (i == 10) {
result = "Ten";
} else if (i == 20) {
result = "Twenty";
} else {
result = i;
}
console.log(result);
}
Or you could just log the desired output directly in each branch of the if/else chain:
for (i = 0; i <= 30; i++) {
if (i == 10) {
console.log("Ten");
} else if (i == 20) {
console.log("Twenty");
} else {
console.log(i);
}
}
I dont think you can change i and expect it to work as usual. hence as soon as you change the value to "TEN", the loop terminates..!!!!
When the counter i gets to ten, you are replacing it with a string, so when the control flow reaches the i++ part, your loop fails. What you should do is assign the value to be printed to another variable that is only used inside the body of the loop.

How to break nested loops in JavaScript? [duplicate]

This question already has answers here:
What's the best way to break from nested loops in JavaScript? [closed]
(18 answers)
Closed 3 years ago.
I tried this:
for(i = 0; i < 5; i++){
for(j = i + 1; j < 5; j++){
break(2);
}
alert(1);
}
only to get:
SyntaxError: missing ; before statement
So, how would I break a nested loop in JavaScript?
You should be able to break to a label, like so:
function foo () {
dance:
for (var k = 0; k < 4; k++) {
for (var m = 0; m < 4; m++) {
if (m == 2) {
break dance;
}
}
}
}
You need to name your outer loop and break that loop, rather than your inner loop - like this.
outer_loop:
for(i=0;i<5;i++) {
for(j=i+1;j<5;j++) {
break outer_loop;
}
alert(1);
}
There are at least five different ways to break out of two or more loops:
1) Set parent(s) loop to the end
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
{
i = 5;
break;
}
}
}
2) Use label
fast:
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
break fast;
}
}
3) Use variable
var exit_loops = false;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
{
exit_loops = true;
break;
}
}
if (exit_loops)
break;
}
4) Use self executing function
(function()
{
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
return;
}
}
})();
5) Use regular function
function nested_loops()
{
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
return;
}
}
}
nested_loops();
See Aaron's. Otherwise:
j=5;i=5 instead of break.
loop1:
for (var i in set1) {
loop2:
for (var j in set2) {
loop3:
for (var k in set3) {
break loop2; // breaks out of loop3 and loop2
}
}
}
code copied from Best way to break from nested loops in Javascript?
Please search before posting a question. The link was the FIRST related question I saw on the left side of this page!
Unfortunately you'll have to set a flag or use labels (think old school goto statements)
var breakout = false;
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
breakout = true;
break;
}
if (breakout) break;
alert(1)
};
The label approach looks like:
end_loops:
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
break end_loops;
}
alert(1)
};
edit: label incorrectly placed.
also see:
http://www.devguru.com/Technologies/ecmascript/quickref/break.html
http://www.daaq.net/old/javascript/index.php?page=js+exiting+loops&parent=js+statements
In my opinion, it's important to keep your construct vocabulary to a minimum. If I can do away with breaks and continues easily, I do so.
function foo ()
{
var found = false;
for(var k = 0; (k < 4 && !found); k++){
for(var m = 0; (m < 4 && !found); m++){
if( m === 2){
found = true;
}
}
}
return found;
}
Be warned, after the loop, m and k are one larger that you might think. This is because m++ and k++ are executed before their loop conditions. However, it's still better than 'dirty' breaks.
EDIT: long comment #Dennis...
I wasn't being 100% serious about being 'dirty', but I still think that 'break' contravenes my own conception of clean code. The thought of having multi-level breaks actually makes me feel like taking a shower.
I find justifying what I mean about a feeling about code because I have coded all life. The best why I can think of it is is a combination of manners and grammar. Breaks just aren't polite. Multi level breaks are just plain rude.
When looking at a for statement, a reader knows exactly where to look. Everything you need to know about the rules of engagement are in the contract, in between the parenthesis. As a reader, breaks insult me, it feels like I've been cheated upon.
Clarity is much more respectful than cheating.
Use function for multilevel loops - this is good way:
function find_dup () {
for (;;) {
for(;;) {
if (done) return;
}
}
}
Wrap in a self executing function and return
(function(){
for(i=0;i<5;i++){
for (j=0;j<3;j++){
//console.log(i+' '+j);
if (j == 2) return;
}
}
})()
You return to "break" you nested for loop.
function foo ()
{
//dance:
for(var k = 0; k < 4; k++){
for(var m = 0; m < 4; m++){
if(m == 2){
//break dance;
return;
}
}
}
}
foo();
break doesn't take parameters. There are two workarounds:
Wrap them in a function and call return
Set a flag in the inner loop and break again right after the loop if the flag is set.
Break 1st loop:
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
//do something
break;
}
alert(1);
};
Break both loops:
for(i=0;i<5;i++)
{
var breakagain = false;
for(j=i+1;j<5;j++)
{
//do something
breakagain = true;
break;
}
alert(1);
if(breakagain)
break;
};
You can break nested for loops with the word 'break', it works without any labels.
In your case you need to have a condition which is sufficient to break a loop.
Here's an example:
var arr = [[1,3], [5,6], [9,10]];
for (var a = 0; a<arr.length; a++ ){
for (var i=0; i<arr[a].length; i++) {
console.log('I am a nested loop and i = ' + i);
if (i==0) { break; }
}
console.log('first loop continues');
}
It logs the following:
> I am a nested loop and i = 0
> first loop continues
> I am a nested loop and i = 0
> first loop continues
> I am a nested loop and i = 0
> first loop continues
The return; statement does not work in this case.
Working pen
function myFunction(){
for(var i = 0;i < n;i++){
for(var m = 0;m < n;m++){
if(/*break condition*/){
goto out;
}
}
}
out:
//your out of the loop;
}

Categories

Resources