Rumah > Artikel > hujung hadapan web > js工具函数-格式化文件大小
ES6代码:
function formatFileSize(fileSize, idx = 0) { const units = ["B", "KB", "MB", "GB"]; if (fileSize < 1024 || idx === units.length - 1) { return fileSize.toFixed(1) + units[idx]; } return formatFileSize(fileSize / 1024, ++idx); }
老版本代码:
function formatFileSize(fileSize, idx) { var units = ["B", "KB", "MB", "GB"]; idx = idx || 0; if (fileSize < 1024 || idx === units.length - 1) { return fileSize.toFixed(1) + units[idx]; } return formatFileSize(fileSize / 1024, ++idx); }