如何在 Javascript 中存储字节数组 [英] How to store a byte array in Javascript

查看:126
本文介绍了如何在 Javascript 中存储字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

推荐答案

通过使用 typed数组,您可以存储这些类型的数组:

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

<头>
类型值范围大小(字节)
Int8Array-128 到 1271
Uint8Array0 到 2551
Uint8ClampedArray0 到 2551
Int16Array-32768 到 327672
Uint16Array0 到 655352
Int32Array-2147483648 到 21474836474
Uint32Array0 到 42949672954
Float32Array-3.4E38 到 3.4E384
Float64Array-1.8E308 到 1.8E3088
BigInt64Array-2^63 到 2^63 - 18
BigUint64Array0 到 2^64 - 18

Stack Snippets 中的演示 &JSFiddle

var array = new Uint8Array(100);
array[42] = 10;
console.log(array[42]);

这篇关于如何在 Javascript 中存储字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆