简体   繁体   中英

Convert ArrayBuffer to Array and vice-versa

I am working with Parallel.js and Q.js to implement "Multithreading" into my application. Because I only can pass serializable objects to Parallel.js and I need to pass an ArrayBuffer I converted the ArrayBuffer to an Uint8Array as an JSON object with this JSON.stringify(new Uint8Array(bytes)) , then in the Parallel.js I convert the JSON Object to an object, then try an Uint8Array and then to its buffer like this

var object = JSON.parse(data[0]);
var bytes = new Uint8Array(Object.keys(object).map(function(k) { return object[k]}));
var buffer = bytes.buffer;

this should usually work because Uint8Array have a prototype called buffer but buffer is always undefined. Object and bytes are correct, when I take a look at the prototype buffer of bytes I can see this message: [Exception: TypeError: Method Uint8Array.buffer called on incompatible receiver #<Uint8Array>] And I really dont know how I should fix this.

Does someone know a fix?

While I'm not sure why that doesn't work, you could convert the values to Base64 and vice versa, as described here :

// encode
var str = base64EncArr(new Uint8Array(4)); // "AAAAAA=="
// decode
var arr = base64DecToArr("AAAAAA=="); // [0, 0, 0, 0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM