const byteConvert = function(bytes) {
if (isNaN(bytes)) {
return '';
}
let symbols = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
let exp = Math.floor(Math.log(bytes)/Math.log(2));
if (exp < 1) {
exp = 0;
}
let i = Math.floor(exp / 10);
bytes = bytes / Math.pow(2, 10 * i);
if (bytes.toString().length > bytes.toFixed(2).toString().length) {
bytes = bytes.toFixed(2);
}
return bytes + ' ' + symbols[i];
};
// 函数调用
byteConvert(bytes);
看到网上字节单位换算的写法,疑惑为啥不直接使用let i = Math.floor(bytes / 1024),使用Math.floor(Math.log(bytes)/Math.log(2))转换的好处是什么呢?
高中数学还给老师了吧,
loga c/loga b=logb c
主要是为了算到底用哪个单位,不用select case了
let i = Math.floor(bytes / 1024)
只是把字节转成kb,如果大于1024kb,还要再除1024,变成MB