简体   繁体   中英

How can I prevent function inside of forEach loop from being called more than once? (For the most part it repeats predictably)

I have a function included in a forEach loop that repeats unpredictably

function setColorColumns(id) {
  getID = id.replace("#", "");
  color_ranges.forEach((item) => {
  colorRangeDivs += `<div class="col ${item.colorGroup.toLowerCase()}" title="${item.colorGroup}" style="background:${item.colorGroup.toLowerCase()}">`;
  colorRangeDivs += `<label for="chk_${getID}_${item.colorGroup.toLowerCase()}">`;
  colorRangeDivs += `<input type="checkbox" id="chk_${getID}_${item.colorGroup.toLowerCase()}"></label></div>\n`;
  });
  return colorRangeDivs;
}

namedColors.forEach((item) => {
  colorDiv = setColorColumns(item.hex);
  colorTable1 = `<div class="color_table_row"><div class="col2"     style="background:${item.hex}">`;
  colorTable2 = `${item.color} (${item.hex})</div>`;
  colorTable3 = `</div>`;
  colorTable += `${colorTable1}${colorTable2}${colorDiv}${colorTable3}`;
});  

The setColorColumns() function creates the checkboxes and that's what repeats for every iteration. If anything, I would think the entire row would repeat, but obviously I'm missing something...

Here's a CodePen version: https://codepen.io/NoahBoddy/pen/WNpzMbV

You can use index inside the foreach loop to solve this issue.


// FOREACH
namedColors.forEach((item, index) => {
  if(index === 0) {
    colorDiv = setColorColumns(item.hex);
  }
  colorTable1 = `<div class="color_table_row"><div class="col2" style="background:${item.hex}">`;
  colorTable2 = `${item.color} (${item.hex})</div>`;
  // this is the line that's getting me in trouble
  colorTable3 = `</div>`;
  colorTable += `${colorTable1}${colorTable2}${colorDiv}${colorTable3}`;
  
});

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