星級展示 函數(shù), 支持半星
function showScore(score, icon) {
if (isNaN(score)) return ''
let maxNum, on, off, half, scoreInt, num, remainder
maxNum = 5
scoreInt = score|0
scoreInt = score|0
remainder = (score*100 - scoreInt*100) / 100
remainder >= .8 ? num = scoreInt+1 : remainder <= .2 ? num = scoreInt : (num = scoreInt, half = 1)
on = new Array(num+1).join(icon[0])
off = new Array(maxNum - num+1 - (half?1:0)).join(icon[1])
return on + (half ? icon[2] : '') + off
}
console.log('%c' +showScore(1.4, ['<星星>', '<無星>', '<半星>']),
'color: #fff; background: #000; font-size: 30px; line-height: 4em; padding: 1em; letter-spacing: .5em;')
效果