將字串 "foo" 轉換為字碼陣列 [102, 111, 111](對應 'f','o','o' 的 Unicode 碼點)。
Array.from + charCodeAtconst str = 'foo';
const codes = Array.from(str, ch => ch.charCodeAt(0));
// 結果: [102, 111, 111]
mapconst codes = [...str].map(ch => ch.charCodeAt(0));
// 結果: [102, 111, 111]
for 迴圈(相容舊環境)function stringToCharCodes(str) {
const codes = [];
for (let i = 0; i < str.length; i++) {
codes.push(str.charCodeAt(i));
}
return codes;
}
原文提到的 JS 1.6/1.7 非標準寫法:
// JS 1.6 (非標準 Array.map 靜態方法)
Array.map('foo', function(x) { return String.charCodeAt(x) }); // [102,111,111]
// JS 1.7 (陣列推導式,已棄用)
[String.charCodeAt(x) for each (x in 'foo')]; // [102,111,111]
charCodeAt 僅回傳 UTF-16 代碼單元,對於增補平面字元(如 Emoji)會產生代理對。若需真正的 Unicode 碼點,請用 codePointAt:
const str = '😀'; // U+1F600
console.log(str.charCodeAt(0)); // 55357 (高代理)
console.log(str.codePointAt(0)); // 128512 (真實碼點)
// 正確取得所有碼點
const codePoints = [...str].map(ch => ch.codePointAt(0));
現代開發建議使用展開運算子配合 map 或 Array.from,語意清晰且效能良好。