javascript - 在字符串和 ArrayBuffers 之间转换

标签 javascript serialization arraybuffer typed-arrays

是否有一种普遍接受的技术可以有效地将 JavaScript 字符串转换为 ArrayBuffers反之亦然?具体来说,我希望能够将 ArrayBuffer 的内容写入 localStorage 然后再读回。

最佳答案

2016 年更新 - 五年过去了,现在规范中出现了新方法(参见下面的支持),可以使用正确的编码在字符串和类型化数组之间进行转换。

文本编码器

TextEncoder represents :

The TextEncoder interface represents an encoder for a specific method, that is a specific character encoding, like utf-8, iso-8859-2, koi8, cp1261, gbk, ... An encoder takes a stream of code points as input and emits a stream of bytes.

自上述内容编写以来的更改说明:(同上)

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) 和 here (whatwg)。

在创建 TextEncoder 的实例后,它将接受一个字符串并使用给定的编码参数对其进行编码:

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"));

如果需要,您当然可以在结果 Uint8Array 上使用 .buffer 参数将底层 ArrayBuffer 转换为不同的 View 。

只需确保字符串中的字符符合编码模式,例如,如果您在示例中使用 UTF-8 范围之外的字符,它们将被编码为两个字节而不是一个。

对于一般用途,您可以对 localStorage 等内容使用 UTF-16 编码。

文本解码器

同样,相反的过程uses the TextDecoder :

The TextDecoder interface represents a decoder for a specific method, that is a specific character encoding, like utf-8, iso-8859-2, koi8, cp1261, gbk, ... A decoder takes a stream of bytes as input and emits a stream of code points.

可以找到所有可用的解码类型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));

MDN StringView 库

这些方法的替代方法是使用 StringView library (许可为 lgpl-3.0)其目标是:

  • 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

提供更大的灵 active 。但是,在现代浏览器中内置 TextEncoder/TextDecoder 时,需要我们链接或嵌入这个库。

支持

截至 2018 年 7 月:

TextEncoder (实验性,在标准轨道上)

 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

关于javascript - 在字符串和 ArrayBuffers 之间转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6965107/

相关文章:

javascript - IE 的 ArrayBuffer.prototype.slice 垫片?

java - 如何在java中使用整数键反序列化Map

Python - 从串行端口读取并编码为 JSON

java - ORM:在 Hibernate/JPA 中用 JSON 代替 LOB

javascript - Dart 变量存储对值的引用

javascript - 比较 : Resizing ArrayBuffer with buffer views (Uint8 vs Float64), 我错过了什么吗?

javascript - 原始数据方法

javascript - jquery 在点击状态切换/停用悬停类

javascript - 所有单选按钮均已选中?

javascript - Grails - 将字符串值从 Controller 传递到 View ,并在 JS 中使用逻辑值