文件大小格式化工具函数
function formatBytes(sizeBytes){
let memoryUnits = [
{
unitName: 'bytes',
threshold: 1024,
},
{
unitName: 'KB',
threshold: 1024,
},
{
unitName: 'MB',
threshold: 1024,
},
{
unitName: 'GB',
threshold: 1024,
},
{
unitName: 'TB',
threshold: 1024,
},
]
let tempFileSize = sizeBytes;
let matchIndex = -1;
for(let i=0, end=false;i<memoryUnits.length ;i++) {
let memoryUnit = memoryUnits[i]
if(tempFileSize <= memoryUnit.threshold){
matchIndex = i;
break;
}
tempFileSize = tempFileSize / memoryUnit.threshold
}
return {
fileSize: tempFileSize + memoryUnits[matchIndex].unitName,
matchUnit: memoryUnits[matchIndex],
originalFileSize: sizeBytes,
};
}
// 示例
formatBytes(1024*3)
标签:文件大小,kb,unitName,mb,bytes,let,threshold,1024
From: https://www.cnblogs.com/XingXiaoMeng/p/16810940.html