charCodeAt(index) 回傳指定索引的 UTF-16 代碼單元值(0~65535)。對於增補字元(>U+FFFF),只能取得高代理項,完整碼點請用 codePointAt()。
str.charCodeAt(index)
NaN。<script>
const str = 'ABC';
console.log(str.charCodeAt(0)); // 65 ('A')
console.log(str.charCodeAt(1)); // 66 ('B')
console.log(str.charCodeAt(2)); // 67 ('C')
console.log(str.charCodeAt(3)); // NaN
// 空白鍵
console.log(' '.charCodeAt(0)); // 32
</script>
<script>
const emoji = '😀'; // U+1F600
console.log(emoji.length); // 2
console.log(emoji.charCodeAt(0)); // 55357 (高代理項 0xD83D)
console.log(emoji.charCodeAt(1)); // 56832 (低代理項 0xDE00)
// 正確取得碼點
console.log(emoji.codePointAt(0)); // 128512 (0x1F600)
console.log(emoji.codePointAt(1)); // 56832 (低代理項)
</script>
function simpleHash(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash |= 0; // 轉 32bit 整數
}
return hash;
}
console.log(simpleHash('hello')); // -123456789 (示例)
| 方法 | 回傳值 | 增補字元支援 | 適用場景 |
|---|---|---|---|
charCodeAt() | UTF-16 代碼單元 (0~65535) | 僅高代理項 | ASCII/BMP 字元、簡單雜湊、舊代碼相容 |
codePointAt() | Unicode 碼點 (0~0x10FFFF) | 完整支援 | Emoji、罕用漢字、國際化處理 |
charCodeAt() 為經典 UTF-16 代碼單元取得方法。處理現代 Unicode 字串(含 Emoji)時,務必改用 codePointAt() 並搭配 `for...of` 迭代,避免代理對拆分錯誤。