1 回答

TA貢獻1829條經驗 獲得超13個贊
String.prototype.charCodeAt(...)僅當字符串僅包含ASCII字符時才能正常工作。TextEncoder如果要處理其他字符,則必須使用標準:
const te = new TextEncoder('utf-8')
function toBinaryRepr(str) {
return Array.from(te.encode(str))
.map(i => i
.toString(2)
.padStart(8, '0'))
.join(' ')
}
// '01100001 01100010 01100011'
toBinaryRepr('abc')
// '01000000 11000010 10101001 11000010 10101110'
toBinaryRepr('@??')
// '11110000 10011111 10011000 10000000 11110000 10011111 10011000 10000100'
toBinaryRepr('??')
警告:TextEncoder在較舊的Node.js版本中不是全局構造函數-如果出現TextEncoder未定義的錯誤提示,請嘗試通過以下方式將其導入:
const { TextEncoder } = require('util')
添加回答
舉報