有時候我們需要把一段字串拆成每個字元對應的編碼值,例如把 "foo" 轉成 [112, 111, 111]。這在處理字元加密、校驗或跨編碼轉換時都可能用得上。以下提供兩種寫法,分別對應不同的 JavaScript 版本。
利用 Array.map 對字串的每個字元套用 charCodeAt:
Array.map('foo', function(x) {
return String.charCodeAt(x);
});
// 結果為 [112, 111, 111]
較新版本支援陣列 comprehension 語法,寫起來更簡潔:
[ String.charCodeAt(x) for each ( x in 'foo' ) ]
// 結果為 [112, 111, 111]
需要留意的是,這兩種寫法依賴較舊的 JS 版本特性。在今日的標準環境中,更通用、相容性更好的做法是先以 split('') 或 [...str] 把字串拆成字元陣列,再用 map 搭配 charCodeAt,例如 [...'foo'].map(c => c.charCodeAt(0)),同樣能得到 [112, 111, 111] 的結果。