← 中文资源

简体中文版本

length 统计 UTF-16 码元而非字符

length 与索引访问按 UTF-16 码元计数,增补字符 emoji 被拆成代理对;展开迭代与 for...of 按完整码点读取,codePointAt 能从低位起点还原码点。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

"café" units: 4 code points: 4
"éclair" units: 6 code points: 6
"🏠" units: 2 code points: 1
"👍🏽" units: 4 code points: 2
"a" units: 1 code points: 1
2 1
d83c 1f3e0
1f44d 1f3fd
👍 1f44d
🏽 1f3fd

实现说明

核心工作在嵌套循环里完成:外层 for (const s of labels),内层 for (const ch of emoji) console.log(ch, ch.codePointAt(0).toString(16));。 演示用的数据放在这几个模块级绑定中:labels、emoji。

使用要点

  • 跑完文件,输出里会留下标记——👍、🏠。

常见问题

包管理器会看到什么?

一份空的依赖清单。示例没有需要抓取的导入。 跨调用保留的状态放在这些顶层绑定里:labels、emoji。

核心语句

const labels = ["café", "éclair", "🏠", "👍🏽", "a"];
const emoji = "👍🏽";

代码示例

const labels = ["café", "éclair", "🏠", "👍🏽", "a"];

for (const s of labels) {
  console.log(JSON.stringify(s), "units:", s.length, "code points:", [...s].length);
}

console.log("👍".length, [..."👍"].length);

// 索引访问按码元切:增补字符被劈成代理对
console.log("🏠"[0].codePointAt(0).toString(16), "🏠".codePointAt(0).toString(16));

// codePointAt 读取完整码点,即使起点落在低位
const emoji = "👍🏽";
console.log(emoji.codePointAt(0).toString(16), emoji.codePointAt(2).toString(16));

// for...of 按码点迭代,不会被代理对劈开
for (const ch of emoji) console.log(ch, ch.codePointAt(0).toString(16));