我得到这段代码通过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;
}
这是正确的做法吗?有没有更简单的方法?
@ al冰岛jm也给出了同样的答案,但以一种“更说教”的方式。谢谢!= D
function formatBytes(numBytes, decPlaces) {
/* Adjust the number of bytes informed for the most appropriate metric according
to its value.
Args:
numBytes (number): The number of bytes (integer);
decPlaces (Optional[number])): The number of decimal places (integer). If
it is "undefined" the value "2" will be adopted.
Returns:
string: The number adjusted together with the most appropriate metric. */
if (numBytes === 0) {
return "0 Bytes";
}
// NOTE: 1 KB is equal to 1024 Bytes. By Questor
// [Ref(s).: https://en.wikipedia.org/wiki/Kilobyte ]
var oneKByte = 1024;
// NOTE: Treats if the "decPlaces" is "undefined". If it is "undefined" the value
// "2" will be adopted. By Questor
if (decPlaces === undefined || decPlaces === "") {
decPlaces = 2;
}
var byteMtrcs = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
// Byte Metrics
// NOTE: Defines the factor for the number of bytes and the metric. By Questor
var mtrcNumbFactor = Math.floor(Math.log(numBytes) / Math.log(oneKByte));
// Metrics Number Factor
return parseFloat((numBytes / Math.pow(oneKByte, mtrcNumbFactor)).
toFixed(decPlaces)) + " " + byteMtrcs[mtrcNumbFactor];
}