取余运算应用(1)-在js中
1、应用1, 让一个数在一个范围内内循环
// 参考: https://zhuanlan.zhihu.com/p/55210125
// eg.让temp在0~5循环
let temp = 0;
setInterval(() => {
temp++;
temp = temp % 6;
console.error(temp);
}, 500);
2、应用2, 防止越界
let arr = [1, 2, 3, 4, 5];
let index = 0;
function getValue() {
index = index % arr.length;
let ret = arr[index];
index++;
return ret;
}
setInterval(() => {
console.error(getValue());
}, 500);
3、应用3, 把一个数限制在0~上限
// 例如:n是随机数,那么n%10就是0~9中的一个数。无论n是多大的数
console.error(Math.floor(Math.random() * 100) % 10);