0

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);

}

1 Answer 1

2

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.