Alexis Wollseifen
Alexis Wollseifen

Reputation: 471

JS : for loop inside forEach

I'm trying to create 4 canvas elements inside several div's using for loop inside forEach.

Here is a sample code:

const wavePart = document.querySelectorAll('.waves');
wavePart.forEach(element => {
  for (i; i < 4; i += 1) {
    let can = document.createElement('canvas');
    element.appendChild(can);
   }
});

This code only create the 4 canvas inside the first wavePart only, it doesn't loop through all containers. Am I doing something wrong?

Upvotes: 1

Views: 5448

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074168

Yes, you're:

  1. Relying on i being defined by some containing code, and

  2. Not setting an initial value for i in your loop

Consequently, i is left at 4 after the first forEach callback, and so on any subsequent callbacks, the for loop body never runs because i < 4 is always false at that point.

Instead, declare i locally within your callback, and set it to 0 to start with:

const wavePart = document.querySelectorAll('.waves');
wavePart.forEach(element => {
  for (let i = 0; i < 4; i += 1) {
  //   ^^^^^^^^^
    let can = document.createElement('canvas');
    element.appendChild(can);
   }
});

Upvotes: 2

Related Questions