gpt4 book ai didi

javascript - 我不明白计算/javascript 的字符串到字节方面

转载 作者:行者123 更新时间:2023-12-02 14:25:15 27 4
gpt4 key购买 nike

两年后回到这个/另一个话题,我看到人们在讨论同样的话题;我还是不明白这是怎么回事。

按照这个SO帖子:

String length in bytes in JavaScript

I want to understand this part of javascript! I am also interested in calculating the kb size of a bitcoin transaction before I push it to the blockchain. The more important of the two though is that I finally understand what these users are doing because its come up more than once and I just don't get it!

我已经尝试了作为答案概述的三个函数,但它们似乎都只是返回 string.length 而我希望它们返回不同的值(字符串的开销以字节/千字节/兆字节为单位) )

function byteCount(s) {
return encodeURI(s).split(/%..|./).length - 1;
}

console.log(byteCount('hello'),'hello'.length);//5,5


function getLengthInBytes(str) {
var b = str.match(/[^\x00-\xff]/g);
return (str.length + (!b ? 0: b.length));
}

console.log(getLengthInBytes('hello'),'hello'.length);//5,5


console.log((new TextEncoder('utf-8').encode('hello')).length,'hello'.length);//5,5

这对我来说毫无意义,这很烦人!显然这些人不会谈论如何获得他们可以通过 string.length 轻松获得的东西 那么他们正在尝试并成功返回什么?

字符串应该是二进制的吗? (像这样:How to convert text to binary code in JavaScript?)

最佳答案

世界上有很多不同的标志。它们不适合一个字节的数据。这就是为什么某些字符使用多个字节的数据的原因。一些示例:“Aüöôś”

关于javascript - 我不明白计算/javascript 的字符串到字节方面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38317328/

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