在字符串和ArrayBuffers之间转换 [英] Converting between strings and ArrayBuffers
问题描述
是否有一种普遍接受的技术可以有效地将JavaScript字符串转换为 ArrayBuffers ,反之亦然?具体来说,我希望能够将ArrayBuffer的内容写入 localStorage
并将其读回。
2016年更新 - 五年后,规范中有新方法(请参阅下面的支持),使用正确的编码在字符串和类型化数组之间进行转换。 / p>
TextEncoder
TextEncoder
接口表示特定方法的编码器,
是特定字符编码,如utf- 8
,编码器将代码点流作为输入和iso-8859-2
,koi8
,
cp1261
,gbk
,...
发出一个字节流。
自上面写的以来更改注释:(同上)
注意:Firefox,Chrome和Opera曾经支持编码
类型其他比utf-8(例如utf-16,iso-8859-2,koi8,cp1261和
gbk)。从Firefox 48 [...],Chrome 54 [...]和Opera 41开始,除了utf-8之外,没有
可用的其他编码类型,以便匹配
规格。*
创建 TextEncoder
的实例后,它将采用一个字符串并使用给定的编码参数对其进行编码:
if(!(窗口中的TextEncoder))alert(抱歉 ,这个浏览器不支持TextEncoder ...); var enc = new TextEncoder(); //总是utf-8console.log(enc.encode(这是转换为Uint8Array的字符串));
然后您当然在结果 Uint8Array上使用
如果需要,将底层 .buffer
参数 ArrayBuffer
转换为另一个视图。
只需确保字符中的字符string遵循编码模式,例如,如果在示例中使用UTF-8范围之外的字符,它们将被编码为两个字节而不是一个。
For一般用途你会使用UTF-16编码,比如 localStorage
。
TextDecoder
同样,相反的过程使用 TextDecoder
:
TextDecoder
interface表示特定方法的解码器,
是特定的char acter编码,如utf-8
,iso-8859-2
,koi8
,
cp1261
,gbk
,...解码器将字节流视为输入并发出
a代码点流。
可以找到所有可用的解码类型这里。
if(!(窗口中的TextDecoder))alert(抱歉,此浏览器不支持TextDecoder ...); var enc = new TextDecoder(utf-8); var arr = new Uint8Array([84,104,105,115,32,105,115,32,97,32,85,105,110,116,56,65,114,114,97,121,32,99,111,110,118,101,114,116,101,100,32,116,111,32,97,32,115,116,114,105,110,103] );的console.log(enc.d ecode(arr));
MDN StringView库
这些的替代方法是使用 StringView
库(许可为lgpl-3.0),其目标是:
- 基于
JavaScript ArrayBuffer接口为字符串(即一个字符代码数组 - JavaScript中的ArrayBufferView)创建类似C的接口
- 创建一个高度可扩展的库,任何人都可以通过向对象StringView.prototype
- 添加方法来扩展这些库,以便为类似字符串的对象创建方法集合(从now:stringViews)严格使用数字
的数组而不是创建新的不可变JavaScript字符串
- 使用除Unicode的默认UTF-16 DOMStrings之外的Unicode编码
提供更多灵活性。但是,它需要我们链接或嵌入此库,而
TextEncoder
/TextDecoder
正在现代内置浏览器。
支持
截至2018年7月:
TextEncoder
(实验,标准轨道)Chrome |边缘| Firefox | IE |歌剧| Safari
---------- | ----------- | ----------- | ---------- - | ----------- | -----------
38 | ? | 19°| - | 25 | -
Chrome / A |边缘/暴民| Firefox / A | Opera / A | Safari / iOS | Webview / A
---------- | ----------- | ----------- | -------- --- | ----------- | -----------
38 | ? | 19°| ? | - | 38
°)18:Firefox 18实现了规范中较早且略有不同的版本
。
WEB工作人员支持:
实验,在标准轨道上
Chrome |边缘| Firefox | IE |歌剧| Safari
---------- | ----------- | ----------- | ---------- - | ----------- | -----------
38 | ? | 20 | - | 25 | -
Chrome / A |边缘/暴民| Firefox / A | Opera / A | Safari / iOS | Webview / A
---------- | ----------- | ----------- | -------- --- | ----------- | -----------
38 | ? | 20 | ? | - | 38
来自MDN的数据 - 'npm i -g mdncomp`由epistemex
Is there a commonly accepted technique for efficiently converting JavaScript strings to ArrayBuffers and vice-versa? Specifically, I'd like to be able to write the contents of an ArrayBuffer to
localStorage
and to read it back.解决方案Update 2016 - five years on there are now new methods in the specs (see support below) to convert between strings and typed arrays using proper encoding.
TextEncoder
The
TextEncoder
interface represents an encoder for a specific method, that is a specific character encoding, likeutf-8
,An encoder takes a stream of code points as input and emits a stream of bytes.iso-8859-2
,koi8
,cp1261
,gbk
, ...Change note since the above was written: (ibid.)
Note: Firefox, Chrome and Opera used to have support for encoding types other than utf-8 (such as utf-16, iso-8859-2, koi8, cp1261, and gbk). As of Firefox 48 [...], Chrome 54 [...] and Opera 41, no other encoding types are available other than utf-8, in order to match the spec.*
*) Updated specs (W3) and here (whatwg).
After creating an instance of the
TextEncoder
it will take a string and encode it using a given encoding parameter:if (!("TextEncoder" in window)) alert("Sorry, this browser does not support TextEncoder..."); var enc = new TextEncoder(); // always utf-8 console.log(enc.encode("This is a string converted to a Uint8Array"));
You then of course use the
.buffer
parameter on the resultingUint8Array
to convert the underlayingArrayBuffer
to a different view if needed.Just make sure that the characters in the string adhere to the encoding schema, for example, if you use characters outside the UTF-8 range in the example they will be encoded to two bytes instead of one.
For general use you would use UTF-16 encoding for things like
localStorage
.TextDecoder
Likewise, the opposite process uses the
TextDecoder
:The
TextDecoder
interface represents a decoder for a specific method, that is a specific character encoding, likeutf-8
,iso-8859-2
,koi8
,cp1261
,gbk
, ... A decoder takes a stream of bytes as input and emits a stream of code points.All available decoding types can be found here.
if (!("TextDecoder" in window)) alert("Sorry, this browser does not support TextDecoder..."); var enc = new TextDecoder("utf-8"); var arr = new Uint8Array([84,104,105,115,32,105,115,32,97,32,85,105,110,116, 56,65,114,114,97,121,32,99,111,110,118,101,114,116, 101,100,32,116,111,32,97,32,115,116,114,105,110,103]); console.log(enc.decode(arr));
The MDN StringView library
An alternative to these is to use the
StringView
library (licensed as lgpl-3.0) which goal is:
- to create a C-like interface for strings (i.e., an array of character codes — an ArrayBufferView in JavaScript) based upon the JavaScript ArrayBuffer interface
- to create a highly extensible library that anyone can extend by adding methods to the object StringView.prototype
- to create a collection of methods for such string-like objects (since now: stringViews) which work strictly on arrays of numbers rather than on creating new immutable JavaScript strings
- to work with Unicode encodings other than JavaScript's default UTF-16 DOMStrings
giving much more flexibility. However, it would require us to link to or embed this library while
TextEncoder
/TextDecoder
is being built-in in modern browsers.Support
As of July/2018:
TextEncoder
(Experimental, On Standard Track)Chrome | Edge | Firefox | IE | Opera | Safari ----------|-----------|-----------|-----------|-----------|----------- 38 | ? | 19° | - | 25 | - Chrome/A | Edge/mob | Firefox/A | Opera/A |Safari/iOS | Webview/A ----------|-----------|-----------|-----------|-----------|----------- 38 | ? | 19° | ? | - | 38 °) 18: Firefox 18 implemented an earlier and slightly different version of the specification. WEB WORKER SUPPORT: Experimental, On Standard Track Chrome | Edge | Firefox | IE | Opera | Safari ----------|-----------|-----------|-----------|-----------|----------- 38 | ? | 20 | - | 25 | - Chrome/A | Edge/mob | Firefox/A | Opera/A |Safari/iOS | Webview/A ----------|-----------|-----------|-----------|-----------|----------- 38 | ? | 20 | ? | - | 38 Data from MDN - `npm i -g mdncomp` by epistemex
这篇关于在字符串和ArrayBuffers之间转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!