简体   繁体   English

如何防止 forEach 循环内的 function 被多次调用? (在大多数情况下,它会重复出现)

[英]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 包含在一个不可预测地重复的 forEach 循环中

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. setColorColumns() function 创建复选框,这就是每次迭代都会重复的内容。 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这是 CodePen 版本: https://codepen.io/NoahBoddy/pen/WNpzMbV

You can use index inside the foreach loop to solve this issue.您可以在foreach循环中使用index来解决此问题。


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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