栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在JavaScript中将字节大小转换为KB,MB,GB的正确方法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在JavaScript中将字节大小转换为KB,MB,GB的正确方法

function bytesToSize(bytes) {
var sizes = [‘Bytes’, ‘KB’, ‘MB’, ‘GB’, ‘TB’];
if (bytes == 0) return ‘0 Byte’;
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ‘ ‘ + sizes[i];
}


注意: 这是原始代码,请在下面使用固定版本。 Aliceljm 不再激活她复制的代码


现在,未缩小固定版本,并且ES6版本:( 按社区)

function formatBytes(bytes, decimals = 2) {    if (bytes === 0) return '0 Bytes';    const k = 1024;    const dm = decimals < 0 ? 0 : decimals;    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];    const i = Math.floor(Math.log(bytes) / Math.log(k));    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];}

**现在,固定版本:

function formatBytes(a,b=2){if(0===a)return"0 Bytes";const c=0>b?0:b,d=Math.floor(Math.log(a)/Math.log(1024));return parseFloat((a/Math.pow(1024,d)).toFixed(c))+" "+["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"][d]}

用法:

// formatBytes(bytes,decimals)formatBytes(1024);       // 1 KBformatBytes('1024');     // 1 KBformatBytes(1234);       // 1.21 KBformatBytes(1234, 3);    // 1.205 KB

演示/来源:

function formatBytes(bytes, decimals = 2) {    if (bytes === 0) return '0 Bytes';    const k = 1024;    const dm = decimals < 0 ? 0 : decimals;    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];    const i = Math.floor(Math.log(bytes) / Math.log(k));    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];}// ** Demo pre **var p = document.querySelector('p'),    input = document.querySelector('input');function setText(v){    p.innerHTML = formatBytes(v);}// bind 'input' eventinput.addEventListener('input', function(){    setText( this.value )})// set initial textsetText(input.value);<input type="text" value="1000"><p></p>

PS:更改

k = 1000
sizes = ["..."]
根据需要( 字节



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/517957.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号