无法在 Javascript 中获取 ArrayBuffer 对象的值

Sve*_*567 4 javascript arrays string json arraybuffer

我有一个ArrayBuffer对象,我需要能够转换为StringJSON,但我不能得到的价值[Int8Array]出来的对象,即使它是明显存在的。

在此处输入图片说明

我已经尝试了所有变体,但它们都返回 undefined

console.log(result);//Returns the array buffer
//Following methods all return undefined?
console.log(result["[[Int8Array]]"]);
console.log(result[[[Int8Array]]]);
console.log(result[[["Int8Array"]]]);
console.log(result[Int8Array]);
console.log(result["Int8Array"]);
Run Code Online (Sandbox Code Playgroud)

如何获取对象中明确可用的所有 Int8Array 或 UInt8Array 值?

Ale*_*shy 8

您需要初始化 anew Uint8Array以获取它们的值,您不能使用您的ArrayBuffer实例直接访问它们。

var buf = new ArrayBuffer(8);
var int8view = new Uint8Array(buf);
console.log(int8view)
Run Code Online (Sandbox Code Playgroud)

JSFiddle:https ://jsfiddle.net/v8m7pjqb/


End*_*ess 8

您可以使用接受 ArrayBuffer(以及 uint8array)的 textDecoder,而不必处理 Uint8array:

var str = new TextDecoder().decode(arrayBuffer)
var json = JSON.parse(str)
Run Code Online (Sandbox Code Playgroud)

如果你想直接获取 json

var json = await new Response(arrayBuffer).json()
Run Code Online (Sandbox Code Playgroud)