From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- files/zh-cn/web/api/textdecoder/index.html | 109 +++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 files/zh-cn/web/api/textdecoder/index.html (limited to 'files/zh-cn/web/api/textdecoder') diff --git a/files/zh-cn/web/api/textdecoder/index.html b/files/zh-cn/web/api/textdecoder/index.html new file mode 100644 index 0000000000..a0e7279ba6 --- /dev/null +++ b/files/zh-cn/web/api/textdecoder/index.html @@ -0,0 +1,109 @@ +--- +title: TextDecoder +slug: Web/API/TextDecoder +tags: + - API + - DOM + - 参考 + - 接口 + - 编码 +translation_of: Web/API/TextDecoder +--- +
{{APIRef("Encoding API")}}
+ +

TextDecoder 接口表示一个文本解码器,一个解码器只支持一种特定文本编码,例如 utf-8iso-8859-2koi8cp1261gbk 等等。解码器将字节流作为输入,并提供代码点流作为输出

+ +

例子

+ +

用类型化数组表示文本

+ +

本示例展示如何解码中文/日语字符,用五个不同的数组类型表示 {{jsxref("Uint8Array")}}, {{jsxref("Int8Array")}}, {{jsxref("Uint16Array")}}, {{jsxref("Int16Array")}}, {{jsxref("Int32Array")}}

+ +
let utf8decoder = new TextDecoder(); // default 'utf-8' or 'utf8'
+
+let u8arr = new Uint8Array([240, 160, 174, 183]);
+let i8arr = new Int8Array([-16, -96, -82, -73]);
+let u16arr = new Uint16Array([41200, 47022]);
+let i16arr = new Int16Array([-24336, -18514]);
+let i32arr = new Int32Array([-1213292304]);
+
+console.log(utf8decoder.decode(u8arr));
+console.log(utf8decoder.decode(i8arr));
+console.log(utf8decoder.decode(u16arr));
+console.log(utf8decoder.decode(i16arr));
+console.log(utf8decoder.decode(i32arr));
+ +

处理非UTF8文本

+ +

在此示例中,我们对俄语文本“Привет,мир!”( "Hello, world.")进行解码。在我们的 {{domxref("TextDecoder/TextDecoder", "TextDecoder()")}} 构造函数中,我们指定Windows-1251字符编码,适用于西里尔字母。

+ +
let win1251decoder = new TextDecoder('windows-1251');
+let bytes = new Uint8Array([207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33]);
+console.log(win1251decoder.decode(bytes)); // Привет, мир!
+ +

构造函数

+ +
+
{{DOMxRef("TextDecoder.TextDecoder", "TextDecoder()")}}
+
返回一个新构造的 TextDecoder,它使用参数中指定的解码方法生成代码点流。
+
+ +

属性

+ +

TextDecoder 接口不继承任何属性。

+ +
+
{{DOMxRef("TextDecoder.prototype.encoding")}}{{ReadOnlyInline}}
+
{{DOMxRef("DOMString")}}所包含的解码器的名称,表示TextDecoder所使用的解码方法的字符串。
+
{{DOMxRef("TextDecoder.prototype.fatal")}}{{ReadOnlyInline}}
+
布尔值,{{jsxref('Boolean')}},是否显示致命错误。
+
{{DOMxRef("TextDecoder.prototype.ignoreBOM")}} {{ReadOnlyInline}}
+
布尔值,{{jsxref('Boolean')}},是否忽略 BOM(byte order marker)标记。
+
+ +

方法

+ +
+
+ +

TextDecoder 接口不继承任何方法

+ +
+
{{DOMxRef("TextDecoder.prototype.decode()")}}
+
返回一个{{DOMxRef("DOMString")}},其中包含使用特定 TextDecoder 对象的方法解码的文本
+
+ +

规范

+ + + + + + + + + + + + + + +
规格状态评论
{{SpecName("Encoding", "#interface-textdecoder", "TextDecoder")}}{{Spec2("Encoding")}}初始定义。
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.TextDecoder")}}

+
+ +

相关链接

+ + -- cgit v1.2.3-54-g00ecf