joshuaiz
joshuaiz

Reputation: 445

Javascript for loop conditional iterations and resetting variable

With the following code, I'm looping through an array of colors (favorites), creating rectangles for a jsPDF document.

After 5 iterations, I want to reset the x variable back to startX and then add 1.875 with each iteration. Likewise for the next 5 iterations: reset x to startX adding 1.875 until 10, then again until 15.

I'm just not having any luck resetting x in these conditionals. I'm sure it's something obvious but what am I missing here?

Or should I structure the loop in a different way?

What I'm trying to accomplish is create up to 3 rows of 5 rectangles. Once I hit 5, start a new row, hence the reset of x which is a page location coordinate.

let startX = 1
let startY = 1

let secondY = 4
let thirdY = 6.5

let n = favorites.length

for (let i = 0, x = startX, y = startY; i < n; x += 1.875, i++) {
    if (i < 5) {
        doc.setFillColor(favorites[i].h)
        doc.rect(x, y, 1.5, 1, 'F')
        doc.text(favorites[i].h.toString(), x, y + 1.5)
    } else if (i >= 5 && i < 10) {
        x = 1 // resets but then doesn't increment
        y = secondY
        doc.setFillColor(favorites[i].h)
        doc.rect(x, y, 1.5, 1, 'F')
        doc.text(favorites[i].h.toString(), x, y + 1.5)
    } else if (i >= 10 && i < 15) {
        x = 1 // resets but then doesn't increment
        y = thirdY
        doc.setFillColor(favorites[i].h)
        doc.rect(x, y, 1.5, 1, 'F')
        doc.text(favorites[i].h.toString(), x, y + 1.5)
    }
}

Upvotes: 3

Views: 572

Answers (2)

Pablo Lozano
Pablo Lozano

Reputation: 10342

You can use the modulo operator (%), and set x and y outside the loop declaration:

const yValues = [1, 4, 6.5];

for (let i = 0 ; i < 15; i++) {
  const x = 1 + ((i%5) * 1.875);
  const y = yValues[Math.floor(i/5)];
  // commented lines to make this example run
  // doc.setFillColor(favorites[i].h)
  // doc.rect(x, y, 1.5, 1, 'F')
  // doc.text(favorites[i].h.toString(), x, y + 1.5)  
  console.log({x,y});
}

Upvotes: 3

B. Shefter
B. Shefter

Reputation: 897

Incrementation in a for loop occur before any commands in the loop. Right now, every iteration in your second and third if blocks resets x to 1, and always does so after x's incrementation in the for loop, thus overwriting it. That's why x isn't changing.

A better approach might be to increment only i, and set x to depend on i's value, something like this:

x = 1 + ((i - 5) * 1.875)
x = 1 + ((i - 10) * 1.875)

And actually, it would be even better to use startX instead of 1:

x = startX + ((i - 5) * 1.875)
x = startX + ((i - 10) * 1.875)

Upvotes: 2

Related Questions