简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM