使用while迴圈,更便捷簡練,程式碼如下:
const countUnit = (value: number, section = 10) => {
let i = 0;
let sum = value / section;
while (sum > section) {
sum = sum / section;
i++;
}
const data = ['十', '百', '千', '萬', '十萬', '百萬', '千萬', '億'];
console.log(data[i], sum);
}
countUnit(10100); // 萬 1.01
同理可用於根據不同範圍值獲取繪製顏色,程式碼如下:
const countColor = (value: number, section: number, colorArray: Array<string>) => {
let i = 0;
let sum = value - section;
while (sum > 0) {
sum = sum - section;
i++;
}
const color = colorArray[i];
console.log(color);
}
countColor(101, 100, ['green', 'blue', 'yellow']); // blue
以上。