loveCoding
loveCoding

Reputation: 115

How to change variable value using loop in JavaScript?

I have variable x, x1, y, y1. I want to change value of variable like below:

First time loop run: x= 0, x1=1, y=0, y=1
Second time loop run: x= 0, x1 = 1, y=2, y=3
Third time loop run: x= 2, x1 = 3, y=0, y=1
fourth time loop run: x= 2, x1 = 3, y=2, y=3

Can anyone help please.

var x,x1,y,y1
for(var i=0; i<4; i++){
x = i;
x1 = i+1;
y = i;
y1= i+1;
console.log(x,x1,y,y1);

}

Upvotes: 0

Views: 908

Answers (1)

junvar
junvar

Reputation: 11604

Assuming you may have more than just 4 iterations, then it's simplest with traditional for loop:

for (let x = 0; x < 4; x += 2) {
  let x1 = x + 1;
  for (let y = 0; y < 4; y+= 2) {
    let y1 = y + 1;
    console.log(x, x1, y, y1);
  }
}

On the other hand, if you have exactly 4 loops, you could just precompute the values

let values = [[0, 1], [2, 3]];
for (let [x, x1] of values)
  for (let [y, y1] of values)
    console.log(x, x1, y, y1);

Extending this approach to more iterations:

let n = 4;
let values = [...Array(n)].map((_, i) => [i * 2, i * 2 + 1]);
for (let [x, x1] of values)
  for (let [y, y1] of values)
    console.log(x, x1, y, y1);

Upvotes: 2

Related Questions