← 中文资源

简体中文版本

codePointAt 读出完整的 emoji 码点

emoji 占两个 UTF-16 码元:length 数码元、charCodeAt 只见半个代理项;codePointAt 读完整码点并与 fromCodePoint 互为往返,for...of 按码点遍历。

阅读英文原文

运行结果

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

units      : 2
codepoint  : 1f600
charCodeAt : d83d
roundtrip  : true
ascii      : 97
iter count : 3 units: 5

实现说明

各个操作都建立在顶层绑定之上:emoji、restored、text。

使用要点

  • 每一步打印都带着自己的标签:charCodeAt :、iter count :。

常见问题

运行前要先安装什么?

什么都不用额外装——运行时自带了代码所需的一切。 文件用顶层绑定保存自己的状态:emoji、restored、text。

核心语句

const restored = String.fromCodePoint(emoji.codePointAt(0));
const emoji = String.fromCodePoint(0x1F600);
const text = emoji + 'x' + emoji;

代码示例

// emoji 占两个 UTF-16 码元:length 数的是码元,codePointAt 读的是完整码点
const emoji = String.fromCodePoint(0x1F600);
console.log('units      :', emoji.length);
console.log('codepoint  :', emoji.codePointAt(0).toString(16));

// charCodeAt 只能看到半个代理项,codePointAt 才能拼回完整码点
console.log('charCodeAt :', emoji.charCodeAt(0).toString(16));

// fromCodePoint 与 codePointAt 互为往返
const restored = String.fromCodePoint(emoji.codePointAt(0));
console.log('roundtrip  :', restored === emoji);

// 普通字符一个码元一个码点
console.log('ascii      :', 'a'.codePointAt(0));

// 用码点遍历:for...of 按码点走,不按码元走
const text = emoji + 'x' + emoji;
console.log('iter count :', [...text].length, 'units:', text.length);