javascript - Forloop困惑

标签 javascript algorithm for-loop

大家好,我在尝试设置这个 forloop 时遇到了问题......但我失败了

如果你看这张图片 here

我需要让这些小点与大数字的颜色相同,具体取决于它们所在的部分。

我正在通过 for 循环将元素添加到首页

for(i = 1; i < 100 ; i++){

 console.log("Number " + i + " with the color red")

}

例如 1-5、11-15、21-25、31-35、41,45 将是红色

我需要使用正则表达式吗?

最佳答案

您可以使用以下函数,将 0 到 99 之间的整数作为输入并输出节号(1 到 4):

((n % 10 > 4) ? 1 : 2) + ((n > 49) ? 2 : 0)

最终结果由两部分组成:

  • ((n % 10 > 4) ? 1 : 2) - 这部分检查数字是否以 0-4 或 5-9 结尾。前者输出1,后者输出2。
  • ((n > 49) ? 2 : 0) - 如果 n 等于或大于 50,则将 2 添加到最终结果(以区分第 1,2 节和第 3,4 节)。

此公式在下面的演示中的getSectionNumber(n) 函数中实现:

var table = document.querySelector('table tbody');

// n is a number between 0 and 99
// output is a section (1 - 4)
function getSectionNumber(n) {
  return ((n % 10 > 4) ? 1 : 2) + ((n > 49) ? 2 : 0);
}

var sectionColors = {
  1: 'darkred',
  2: 'darkblue',
  3: 'darkgreen',
  4: 'yellow'
};

for(var i = 0; i < 10; i++) {
  var row = document.createElement('tr');
  table.appendChild(row);
  for(var j = 0; j < 10; j++) {
    var cell = document.createElement('td');
    var cellId = i*10 + j
    cell.textContent = cellId;
    cell.style.backgroundColor = sectionColors[getSectionNumber(cellId)];
    row.appendChild(cell);
  }
}
<table>
  <tbody>
  </tbody>
</table>

关于javascript - Forloop困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40188961/

相关文章:

javascript - 忽略括号外的操作

javascript - 将字符串传递给 javascript 函数参数被解析为整数

javascript - Ext.JS - 网格不加载存储值

html - 交叉渐变关键帧百分比算法

javascript - for循环在字符串的第一个字母处停止?

javascript - 允许退格的javascript中的正则表达式

c++ - 在树结构中搜索数据

algorithm - 寻找包含两个节点的最短循环

python - 有没有一种更快的方法来创建空数组的元素数组而不使用 for 循环

javascript - JS for循环如何获取第一个值