function converToBytes(size, unit) {
const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const index = units.indexOf(unit.toUpperCase());
if (index < 0) {
throw new Error('Invalid unit');
}
return Math.floor(size * Math.pow(1024, index));
}
console.log(converToBytes(1, 'B')); // 1
console.log(converToBytes(1, 'KB')); // 1024
console.log(converToBytes(1, 'MB')); // 1048576
console.log(converToBytes(1, 'GB')); // 1073741824
console.log(converToBytes(1, 'TB')); // 1099511627776
js实现将字节转换成单位
最新推荐文章于 2026-07-28 21:27:43 发布
该函数将数字从一种存储单位转换为另一种,支持B,KB,MB,GB,TB,PB,EB,ZB,YB之间的转换。它基于2的幂次进行计算,并使用Math.pow方法。如果输入的单位无效,函数会抛出错误。

5069

被折叠的 条评论
为什么被折叠?



