萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 將字串轉為 Unicode 字碼陣列的多種方法

需求場景

將字串 "foo" 轉換為字碼陣列 [102, 111, 111](對應 'f','o','o' 的 Unicode 碼點)。

方法一:ES6 / 現代瀏覽器 Array.from + charCodeAt

const str = 'foo';
const codes = Array.from(str, ch => ch.charCodeAt(0));
// 結果: [102, 111, 111]

方法二:展開運算子 + map

const 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]

補充:取得 Unicode 碼點(支援 Emoji)

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,語意清晰且效能良好。

copyright © 萬盛學電腦網 all rights reserved