取餘運算應用(1)-在js中
阿新 • • 發佈:2020-12-29
技術標籤:Threejs-Shader
取餘運算應用(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);