首页 > 其他分享 >js 文件大小bytes自动格式化为kb,mb单位。

js 文件大小bytes自动格式化为kb,mb单位。

时间:2022-10-20 19:14:13浏览次数:54  
标签:文件大小 kb unitName mb bytes let threshold 1024

文件大小格式化工具函数

		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

相关文章