By using typed arrays, you can store arrays of these types:
| Type | Value Range | Size(bytes) |
|---|---|---|
Int8Array |
-128 to 127 | 1 |
Uint8Array |
0 to 255 | 1 |
Uint8ClampedArray |
0 to 255 | 1 |
Int16Array |
-32768 to 32767 | 2 |
Uint16Array |
0 to 65535 | 2 |
Int32Array |
-2147483648 to 2147483647 | 4 |
Uint32Array |
0 to 4294967295 | 4 |
Float32Array |
-3.4E38 to 3.4E38 | 4 |
Float64Array |
-1.8E308 to 1.8E308 | 8 |
BigInt64Array |
-2^63 to 2^63 - 1 | 8 |
BigUint64Array |
0 to 2^64 - 1 | 8 |
Demo in Stack Snippets & JSFiddle
var array = new Uint8Array(100);
array[42] = 10;
console.log(array[42]);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Answer from Kendall Frey on Stack OverflowBy using typed arrays, you can store arrays of these types:
| Type | Value Range | Size(bytes) |
|---|---|---|
Int8Array |
-128 to 127 | 1 |
Uint8Array |
0 to 255 | 1 |
Uint8ClampedArray |
0 to 255 | 1 |
Int16Array |
-32768 to 32767 | 2 |
Uint16Array |
0 to 65535 | 2 |
Int32Array |
-2147483648 to 2147483647 | 4 |
Uint32Array |
0 to 4294967295 | 4 |
Float32Array |
-3.4E38 to 3.4E38 | 4 |
Float64Array |
-1.8E308 to 1.8E308 | 8 |
BigInt64Array |
-2^63 to 2^63 - 1 | 8 |
BigUint64Array |
0 to 2^64 - 1 | 8 |
Demo in Stack Snippets & JSFiddle
var array = new Uint8Array(100);
array[42] = 10;
console.log(array[42]);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
var array = new Uint8Array(100);
array[10] = 256;
array[10] === 0 // true
I verified in firefox and chrome, its really an array of bytes :
var array = new Uint8Array(1024*1024*50); // allocates 50MBytes
How can I create byte array in js?
[JavaScript] What is a byte? How do the Uint8Array and TextEncoder/TextDecoder functions relate to it?
construct-js: A library for creating byte level data structures
Hello,
I am trying very hard to understand these things, but the confusing articles online aimed at people with CS experience aren't helping.
1.) I am told that a Uint8Array and similar data types contain a list of "bytes". How is this different than a normal list of numbers?
2.) What does it mean to convert this "array of bytes" (which seems be just an array of integers) using TextDecoder.decode?
-
Going deeper, what even is a decoder/encoder? If I use TextDecoder.decode to decode an array of bytes as UTF-8 and get a string back, what in the world is actually going on? Does it look at every X numbers and perform an operation?
Any resources on this would be much appreciate too.
Thanks!