在 Javascript 中将 Uint8Array 转换为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29676635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Uint8Array to Array in Javascript
提问by Kysil Ivan
I have Uint8Array instance that contains binary data of some file.
I want to send data to the server, where it will be deserialized as byte[].
But if I send Uint8Array, I have deserialization error.
我有包含某个文件的二进制数据的 Uint8Array 实例。
我想将数据发送到服务器,在那里它将被反序列化为 byte[]。
但是,如果我发送 Uint8Array,则会出现反序列化错误。
So, I want to convert it to Array, as Array is deserialized well.
I do it as follows:
所以,我想将它转换为 Array,因为 Array 反序列化得很好。
我这样做:
function uint8ArrayToArray(uint8Array) {
var array = [];
for (var i = 0; i < uint8Array.byteLength; i++) {
array[i] = uint8Array[i];
}
return array;
}
This function works fine, but it is not very efficient for big files.
此功能运行良好,但对于大文件效率不高。
Question: Is there more efficient way to convert Uint8Array --> Array?
问题:有没有更有效的方法来转换 Uint8Array --> Array?
回答by darthmaim
You can use the following in environments that support Array.fromalready (ES6)
您可以在Array.from已经支持(ES6) 的环境中使用以下内容
var array = Array.from(uint8Array)
When that is not supported you can use
如果不支持,您可以使用
var array = [].slice.call(uint8Array)
回答by Vinicio Ajuchan
There is a method of Uint8Array using the prototype (but it only supported by Firefox and Chrome):
有一个使用原型的 Uint8Array 方法(但只支持 Firefox 和 Chrome):
TypedArray.prototype.entries() --> it returns a array.
TypedArray.prototype.entries() --> 它返回一个数组。
Check it out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/entries
检查一下:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/entries

