我得到这段代码通过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];
}
我最初在一个文件上传项目中使用@ al冰岛jm的答案,但最近遇到了一个问题,一个文件是0.98kb,但读取为1.02mb。下面是我现在使用的更新代码。
function formatBytes(bytes){
var kb = 1024;
var ndx = Math.floor( Math.log(bytes) / Math.log(kb) );
var fileSizeTypes = ["bytes", "kb", "mb", "gb", "tb", "pb", "eb", "zb", "yb"];
return {
size: +(bytes / kb / kb).toFixed(2),
type: fileSizeTypes[ndx]
};
}
在像这样添加文件之后,上面的函数将被调用
// In this case `file.size` equals `26060275`
formatBytes(file.size);
// returns `{ size: 24.85, type: "mb" }`
当然,Windows读取的文件为24.8mb,但我对额外的精度很满意。
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]} ';
}