如果二進制資料實際上是字串會如何?例如,我們收到一個包含文字資料的檔案。
內建的 TextDecoder 物件允許我們將值讀取到實際的 JavaScript 字串中,並提供緩衝區和編碼。
我們首先需要建立它
let decoder = new TextDecoder([label], [options]);
標籤
– 編碼,預設為utf-8
,但big5
、windows-1251
和許多其他編碼也受支援。選項
– 選擇性物件致命
– 布林值,如果為true
,則對無效(無法解碼)字元擲回例外,否則(預設)將它們替換為字元\uFFFD
。忽略 BOM
– 布林值,如果為true
,則忽略 BOM(一個選擇性的位元組順序 Unicode 標記),很少需要。
…然後解碼
let str = decoder.decode([input], [options]);
輸入
– 要解碼的BufferSource
。選項
– 選擇性物件串流
– 如果解碼器
會重複呼叫並提供資料的區塊,則對串流解碼為 true。在這種情況下,多位元組字元偶爾會在區塊之間分割。此選項會指示TextDecoder
記住「未完成」的字元,並在收到下一個區塊時解碼它們。
例如
let uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
alert( new TextDecoder().decode(uint8Array) ); // Hello
let uint8Array = new Uint8Array([228, 189, 160, 229, 165, 189]);
alert( new TextDecoder().decode(uint8Array) ); // 你好
我們可以透過為其建立子陣列檢視來解碼緩衝區的一部分
let uint8Array = new Uint8Array([0, 72, 101, 108, 108, 111, 0]);
// the string is in the middle
// create a new view over it, without copying anything
let binaryString = uint8Array.subarray(1, -1);
alert( new TextDecoder().decode(binaryString) ); // Hello
TextEncoder
TextEncoder 執行相反的操作,將字串轉換為位元組。
語法為
let encoder = new TextEncoder();
它支援的唯一編碼是「utf-8」。
它有兩個方法
編碼 (str)
– 從字串傳回Uint8Array
。編碼至 (str, 目標)
– 將str
編碼至目標
,而目標
必須是Uint8Array
。
let encoder = new TextEncoder();
let uint8Array = encoder.encode("Hello");
alert(uint8Array); // 72,101,108,108,111
留言
<code>
標籤,若要插入多行程式碼,請將它們包在<pre>
標籤中,若要插入超過 10 行程式碼,請使用沙盒 (plnkr、jsbin、codepen…)