写法一:
function formatSizeUnits(kb) {let units = ['KB', 'MB', 'GB', 'TB', 'PB','EB','ZB','YB'];let unitIndex = 0;while (kb >= 1024 && unitIndex < units.length - 1) {kb /= 1024;unitIndex++;}return `${kb.toFixed(2)} ${units[unitIndex]}`;
}
console.log(formatSizeUnits(1034000320))
写法二:
function formatSizeUnits(kb) {let units = ['KB', 'MB', 'GB', 'TB', 'PB','EB','ZB','YB'];let unitIndex = 0;let unit = ''for(let i=1;i<units.length+1;i++){if(kb>=1024&i<units.length){kb=kb/1024;unit = units[i]// console.log('if',kb,i,unit)} else {unit = units[i-1]// console.log('else',kb,i,unit)return `${kb.toFixed(2)} ${unit}`;}}}
console.log(formatSizeUnits(1034000320))