假设我有以下TypeScript代码(以字符串表示):
function greet(name: string): void {
console.log(`Hello ${name}!`);
}
我如何以编程方式确定此字符串中有多少千字节?
我当前正在使用以下公式:
// NOTE: "string.length" represents the number of bytes in the string
const KB: number = (string.length / 1024).toFixed(2);
问题在于该数字经常看起来太大或太小而无法正确计算。
当我将字符串放在一个空文件中并保存时,我的文件管理器的属性输出的大小会完全不同,有时会有2-20 KB的大小。
我在做什么错了,我应该使用1000
个字节代表一个千字节而不是1024
吗?
有什么我不能正确理解的东西吗?
答案 0 :(得分:2)
JavaScript字符串中的字符使用Unicode
进行编码,每个引擎都有自己的字符集,最受欢迎的是UTF-16
。因此,每个字符都保存2 bytes
数据。要查找字符串使用的总数kilobytes
,请找到使用的bytes
数并将其除以1024
const string = "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc";
const b = string.length * 2;
const kb = (b / 1024).toFixed(2);
console.log(`${kb}KB`);