如何在 Javascript 中存储字节数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12332002/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:44:24  来源:igfitidea点击:

How to store a byte array in Javascript

javascriptarrayshtmlbytearraybyte

提问by Kendall Frey

I'm going to be storing a large array of byte values (most likely over a million) in Javascript. If I use a normal array with normal numbers, that will take 8 MB, because numbers are stored as IEEE doubles, but if I can store it as bytes, it will be only 1 MB.

我将在 Javascript 中存储大量字节值(很可能超过一百万)。如果我使用带有普通数字的普通数组,那将需要 8 MB,因为数字存储为 IEEE 双精度数,但如果我可以将其存储为字节,则只有 1 MB。

I'd like to avoid wasting that much space for obvious reasons. Is there a way to store bytes as bytes instead of doubles? Browser compatibility isn't an issue for me, as long as it works in Chrome. This is in HTML5, if that makes a difference.

由于显而易见的原因,我想避免浪费那么多空间。有没有办法将字节存储为字节而不是双精度?浏览器兼容性对我来说不是问题,只要它在 Chrome 中工作即可。这是在 HTML5 中,如果这有区别的话。

回答by Kendall Frey

By using typed arrays, you can store arrays of these types:

通过使用类型化数组,您可以存储以下类型的数组:

  • Int8
  • Uint8
  • Int16
  • Uint16
  • Int32
  • Uint32
  • Float32
  • Float64
  • 整数8
  • 单位8
  • 整数16
  • 单位16
  • 整数32
  • 单位32
  • 浮点数 32
  • Float64

For example:

例如:

?var array = new Uint8Array(100);
array[42] = 10;
alert(array[42]);?

See it in action here.

这里查看它的实际效果。

回答by reuns

var array = new Uint8Array(100);    
array[10] = 256;
array[10] === 0 // true

I verified in firefox and chrome, its really an array of bytes :

我在 Firefox 和 chrome 中进行了验证,它确实是一个字节数组:

var array = new Uint8Array(1024*1024*50);  // allocates 50MBytes

回答by Hew Wolff

You could store the data in an array of strings of some large fixed size. It should be efficient to access any particular character in that array of strings, and to treat that character as a byte.

您可以将数据存储在一些大的固定大小的字符串数组中。访问该字符串数组中的任何特定字符并将该字符视为字节应该是有效的。

It would be interesting to see the operations you want to support, perhaps expressed as an interface, to make the question more concrete.

看到您想要支持的操作(可能表示为接口)以使问题更加具体,会很有趣。