问题描述
我有Uint8Array实例,其中包含某些文件的二进制数据.
我想将数据发送到服务器,在服务器上将其反序列化为byte [].
但是,如果我发送Uint8Array,则会出现反序列化错误.
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.
因此,我想将其转换为Array,因为Array已很好地反序列化.
我这样做如下:
So, I want to convert it to Array, as Array is deserialized well.
I do it as follows:
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.
问题:是否有更有效的方法来转换Uint8Array-> Array?
推荐答案
您可以在支持 Array.from
已经(ES6)
You can use the following in environments that support Array.from
already (ES6)
var array = Array.from(uint8Array)
如果不支持,则可以使用
When that is not supported you can use
var array = [].slice.call(uint8Array)
这篇关于将Uint8Array转换为Javascript中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!