示例工程 02-values-types-equality
另有 1 个文件未随站点发布(平台工程、二进制或超过 200KB)。
02-values-types-equality/05-string-utf16/main.js
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
// main.js —— 字符串是 UTF-16 码元序列,不是码点序列
// length 数的是「码元」,而人眼看到的是「字符(码点/grapheme)」。
export function checks() {
const emoji = '😀'; // U+1F600,UTF-16 里占两个码元
const composed = 'é'; // U+00E9,单码点
const combined = 'e\u0301'; // e + 组合重音符,两个码点
return [
{ label: "'abc'.length", value: 'abc'.length },
{ label: "'😀'.length", value: emoji.length },
{ label: "[...'😀'].length", value: [...emoji].length },
{ label: "'😀'.codePointAt(0).toString(16)", value: emoji.codePointAt(0).toString(16) },
{ label: "'😀'.charCodeAt(0).toString(16)", value: emoji.charCodeAt(0).toString(16) },
{ label: "'😀'[0].length", value: emoji[0].length },
{ label: "[...'😀a'].reverse().join('')", value: [...'😀a'].reverse().join('') },
{ label: "'😀a'.split('').reverse().join('')", value: '😀a'.split('').reverse().join('') },
{
label: "'😀a'.split('').reverse().join('') === 'a😀'",
value: '😀a'.split('').reverse().join('') === 'a😀',
},
{ label: "'é' === 'e\\u0301'", value: composed === combined },
{ label: "'é' === 'e\\u0301'.normalize('NFC')", value: composed === combined.normalize('NFC') },
{ label: "'é'.length / 'e\\u0301'.length", value: `${composed.length} / ${combined.length}` },
{ label: "TextEncoder().encode('😀').length", value: new TextEncoder().encode(emoji).length },
];
}
export function run(log = console.log) {
const rows = checks();
log('表达式 => 结果');
for (const r of rows) log(`${r.label} => ${r.value}`);
log('-'.repeat(66));
log("要点:String.length 数 UTF-16 码元;按码点遍历用 [...str]、Array.from(str);字节长度用 TextEncoder。");
return rows;
}