JavaScript 字符串的安全长度是多少?

What is a safe length of JavaScript strings?

考虑到 charAt()charCodeAt()codePointAt(),我发现参数含义之间存在差异。在我真正考虑之前,我认为您始终可以安全地访问 length-1 处的角色。但我读到 charCodeAt() 和 codePointAt() 之间的区别是 charCodeAt() 指的是 16 位(字节对)所以除了阅读 i 你还需要 i+1 如果它们是代理对(与 UTF-16 的方法一样)。而 codePointAt() 需要一个引用 UTF-8 字符位置(从零开始)的参数。所以现在我很纠结 length 是计算字符数,还是字节对数 UTF-16 风格。我相信 JavaScript 将字符串保存为 UTF-16,但是在具有大量 4 字节字符的字符串上使用 length-1 和 codePointAt() 函数将结束字符串!!

使用 [...str].length 作为字符数。

var mb = "";
console.log(mb.length);
console.log([...mb].length); // "real" length (ES6)
console.log(mb.charAt(0)); // The first two byte
console.log(mb.codePointAt(0)); // The first two byte
console.log(mb.codePointAt(1)); // The second two byte
console.log(mb.charCodeAt(0)); // The four bytes combined (ES6)
console.log(mb.charCodeAt(1)); // The second two byte (ES6)

length of strings 被计入 16 位无符号整数值(“元素”) 代码单元(其中一起形成一个有效或无效的 UTF16 代码单元序列),它的索引也是如此。我们也可以称它们为 "characters".

无论您是否访问它们都没有关系as properties or via charAt, chatCodeAt and codePointAtlength - 1 将始终是一个有效索引。然而,代码点可能被编码为跨越两个索引的代理对。没有内置方法来测量它们的数量,但默认的字符串迭代器会生成它们,因此您可以使用 for … of 循环对它们进行计数。