我得到这段代码通过PHP隐蔽大小字节。

现在我想使用JavaScript将这些大小转换为人类可读的大小。我尝试将这段代码转换为JavaScript,看起来像这样:

function formatSizeUnits(bytes){
  if      (bytes >= 1073741824) { bytes = (bytes / 1073741824).toFixed(2) + " GB"; }
  else if (bytes >= 1048576)    { bytes = (bytes / 1048576).toFixed(2) + " MB"; }
  else if (bytes >= 1024)       { bytes = (bytes / 1024).toFixed(2) + " KB"; }
  else if (bytes > 1)           { bytes = bytes + " bytes"; }
  else if (bytes == 1)          { bytes = bytes + " byte"; }
  else                          { bytes = "0 bytes"; }
  return bytes;
}

这是正确的做法吗?有没有更简单的方法?


当前回答

function bytes2Size(byteVal){
    var units=["Bytes", "KB", "MB", "GB", "TB"];
    var kounter=0;
    var kb= 1024;
    var div=byteVal/1;
    while(div>=kb){
        kounter++;
        div= div/kb;
    }
    return div.toFixed(1) + " " + units[kounter];
}

其他回答

var大小=[“字节”,“知识库”,“m”,“g”,“结核”,“铅”、“海尔哥哥”,“ZB”,“YB”); 函数formatBytes(字节,小数){ For (var I = 0, r = bytes, b = 1024;R > b;I ++) r /= b; 返回' ${parseFloat(r.toFixed(decimal))} ${SIZES[i]} '; }

function formatBytes(bytes) {
    var marker = 1024; // Change to 1000 if required
    var decimal = 3; // Change as required
    var kiloBytes = marker; // One Kilobyte is 1024 bytes
    var megaBytes = marker * marker; // One MB is 1024 KB
    var gigaBytes = marker * marker * marker; // One GB is 1024 MB
    var teraBytes = marker * marker * marker * marker; // One TB is 1024 GB

    // return bytes if less than a KB
    if(bytes < kiloBytes) return bytes + " Bytes";
    // return KB if less than a MB
    else if(bytes < megaBytes) return(bytes / kiloBytes).toFixed(decimal) + " KB";
    // return MB if less than a GB
    else if(bytes < gigaBytes) return(bytes / megaBytes).toFixed(decimal) + " MB";
    // return GB if less than a TB
    else return(bytes / gigaBytes).toFixed(decimal) + " GB";
}
const byteConversion = (bytes: number, decimals = 2) => {
if (bytes === 0) return '0 B';

const kiloByte = 1000;
const decimal = decimals < 0 ? 0 : decimals;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

const i: number = Math.floor(Math.log(bytes) / Math.log(kiloByte));

return `${parseFloat((bytes / kiloByte ** i).toFixed(decimal))} ${sizes[i]}`;

};

这里有一句话:

val => ['Bytes','Kb','Mb','Gb','Tb'][Math.floor(Math.log2(val)/10)]

甚至:

v => 'BKMGT'[~~(Math.log2(v)/10)]

与数:

function shortenBytes(n) {
    const k = n > 0 ? Math.floor((Math.log2(n)/10)) : 0;
    const rank = (k > 0 ? 'KMGT'[k - 1] : '') + 'b';
    const count = Math.floor(n / Math.pow(1024, k));
    return count + rank;
}

我让算法快了7倍(就像忍者一样):

function rafaelFormatBytes(number){ if(number == null || number === undefined || number <= 0) { return '0 Bytes'; } var scaleCounter = 0; var scaleInitials = [' Bytes',' KB',' MB',' GB',' TB',' PB',' EB',' ZB',' YB']; while (number >= 1024 && scaleCounter < scaleInitials.length - 1){ number /= 1024; scaleCounter++; } if(scaleCounter >= scaleInitials.length) scaleCounter = scaleInitials.length - 1; var compactNumber = number.toFixed(2) .replace(/\.?0+$/,'') .replace(/\B(?=(\d{3})+(?!\d))/g, ","); compactNumber += scaleInitials[scaleCounter]; return compactNumber.trim(); } var testNum = 0; var startTime, endTime; function start() { startTime = new Date(); }; function end() { endTime = new Date(); var timeDiff = endTime - startTime; //in ms // strip the ms timeDiff /= 1000; // get seconds var seconds = Math.round(timeDiff, 5); console.log(timeDiff + " seconds"); } function formatBytes(a,b=2,k=1024){with(Math){let d=floor(log(a)/log(k));return 0==a?"0 Bytes":parseFloat((a/pow(k,d)).toFixed(max(0,b)))+" "+["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"][d]}} console.log(formatBytes(1000000000000000000000000000)); console.log(rafaelFormatBytes(1000000000000000000000000000)); start(); for(i=0; i<100000; i++){ formatBytes(1000000000000000); } end(); start(); for(i=0; i<100000; i++){ rafaelFormatBytes(1000000000000000); } end();

... 输出:

827.18 YB
827.18 YB
0.293 seconds
0.039 seconds

耶稣基督!