后台传递的数据的b,前端按大小转换KB,MB,GB?

对于我之前的代码

js
复制代码
function formatSizeUnits(kb) { var result = ''; if (kb < 1024) { result = kb + ' KB'; } else if (kb < 1024 * 1024) { result = (kb / 1024).toFixed(2) + ' MB'; } else if (kb < 1024 * 1024 * 1024) { result = (kb / 1024 / 1024).toFixed(2) + ' GB'; } else { result = (kb / 1024 / 1024 / 1024).toFixed(2) + ' TB'; } return result; }

对吧,这代码一看就是初学者的,只为了完成业务而封装的一个转换类型的函数

再看看大佬的两种方案

js
复制代码
function formatSizeUnits(kb) { let units = ['KB', 'MB', 'GB', 'TB', 'PB']; let unitIndex = 0; while (kb >= 1024 && unitIndex < units.length - 1) { kb /= 1024; unitIndex++; } return `${kb.toFixed(2)} ${units[unitIndex]}`; }
js
复制代码
const formatSizeUnits = (kb) => { if (!kb) return '0 KB'; let unit = ['KB', 'MB', 'GB', 'TB', 'PB']; const step = 1024; const e = Math.floor(Math.log(kb) / Math.log(step)); return `${(kb / step ** Math.floor(e)).toFixed(2)} ${unit[e]}`; };

一目了然,大家还有什么好的方法

0个评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
下载 APP