js - 星级展示

星级展示 函数, 支持半星

    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;')
效果

你可能感兴趣的:(js - 星级展示)