← 中文资源

简体中文版本

fromCodePoint 重建 emoji 序列

String.fromCodePoint 接受代理对与 ZWJ 连接序列:一个家庭 emoji 用 5 个码点拼成但 str.length 是 8(UTF-16 单元数),展开迭代才数出 5 个码点。

阅读英文原文

运行结果

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

rendered: 👨‍👩‍👧
UTF-16 code units (str.length): 8
code points ([...str]): 5
single emoji: 2 1
mixed ABC+emoji length: 4 code points: 3

实现说明

顶层就这几处状态:label、mixing。

使用要点

  • 演示输出是带标签的(rendered:、UTF-16 code units (str.length):、code points ([...str]):),每个操作都会留下自己的一行标注。

常见问题

这个示例需要哪些包?

一个都不用。代码用到的符号都在标准库里解析。 跨调用保留的状态放在这些顶层绑定里:label、mixing。

核心语句

const label = String.fromCodePoint(0x1f468, 0x200d, 0x1f469, 0x200d, 0x1f467);
const mixing = String.fromCodePoint(65, 0x1f600, 66);

代码示例

const label = String.fromCodePoint(0x1f468, 0x200d, 0x1f469, 0x200d, 0x1f467);
console.log('rendered:', label);
console.log('UTF-16 code units (str.length):', label.length);
console.log('code points ([...str]):', [...label].length);

// 单个码点超过 BMP 会占两个 UTF-16 单元
console.log('single emoji:', String.fromCodePoint(0x1f600).length, [...'\u{1f600}'].length);

// 混合 BMP 与增补平面:length 与码点数分道扬镳
const mixing = String.fromCodePoint(65, 0x1f600, 66);
console.log('mixed ABC+emoji length:', mixing.length, 'code points:', [...mixing].length);