gpt4 book ai didi

javascript - 如何使用 TypeScript 确定一串代码中有多少千字节?

转载 作者:行者123 更新时间:2023-11-30 14:03:05 25 4
gpt4 key购买 nike

假设我有以下 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 来表示千字节吗?

最佳答案

JavaScript 字符串中的字符使用Unicode 编码,每个引擎都有自己的字符集,最流行的是UTF-16。因此,每个字符包含 2 个字节 的数据。要查找字符串使用的总 kilobytes,请找到正在使用的 bytes 数并将其除以 1024

const string = "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc";

const b = string.length * 2;
const kb = (b / 1024).toFixed(2);

console.log(`${kb}KB`);

关于javascript - 如何使用 TypeScript 确定一串代码中有多少千字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55957787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com