大家好,我在尝试设置这个 forloop 时遇到了问题......但我失败了
我需要让这些小点与大数字的颜色相同,具体取决于它们所在的部分。
我正在通过 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/