TextDecoder: decode() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流瀏覽器均已支援。

注意:此功能在 Web Workers 中可用。

TextDecoder.decode() 方法返回一個字串,其中包含從作為引數傳入的緩衝區解碼出的文字。

解碼方法在當前的 TextDecoder 物件中定義。這包括了資料的預期編碼方式,以及如何處理解碼錯誤。

語法

js
decode()
decode(buffer)
decode(buffer, options)

引數

buffer 可選

一個 ArrayBuffer、一個 TypedArray 或一個 DataView 物件,包含要解碼的編碼文字。

options 可選

具有以下屬性的物件:

stream

一個布林標誌,指示在後續呼叫 decode() 時是否還有更多資料。如果資料分塊處理,則設定為 true;如果是最後一塊或資料未分塊,則設定為 false。預設為 false

異常

TypeError

當屬性 TextDecoder.fataltrue 時,如果發生解碼錯誤則丟擲此異常。

返回值

字串。

示例

此示例對歐元符號 € 進行編碼和解碼。

HTML

html
<p>Encoded value: <span id="encoded-value"></span></p>
<p>Decoded value: <span id="decoded-value"></span></p>

JavaScript

js
const encoder = new TextEncoder();
const array = encoder.encode("€"); // Uint8Array(3) [226, 130, 172]
document.getElementById("encoded-value").textContent = array;

const decoder = new TextDecoder();
const str = decoder.decode(array); // String "€"
document.getElementById("decoded-value").textContent = str;

結果

規範

規範
編碼
# ref-for-dom-textdecoder-decode①

瀏覽器相容性

另見