Typed Arrays provide a means to look at raw binary contents of data through a particular typed view. For example, if we want to look at our raw binary data a byte at a time, we can use a Uint8Array (Uint8 describes an 8-bit unsigned integer value, commonly known as a byte). If we want to read the raw data as an array of floating point numbers, we can use a Float32Array (Float32 describes a 32-bit IEE754 floating point value, commonly known as a floating point number). The following types are supported:
Each array type is a view over an ArrayBuffer. The ArrayBuffer is a reference to the raw binary data, but it does not provide any direct way to interact with the data. Creating a TypedArray view of the ArrayBuffer provides access to read from and write to the binary contents.
The example below creates a new ArrayBuffer from scratch and interprets its contents in a few different ways:
Array Type | Element size and description |
---|---|
Int8Array | 8-bit signed integer |
Uint8Array | 8-bit unsigned integer |
Int16Array | 16-bit signed integer |
Uint16Array | 16-bit unsigned integer |
Int23Array | 32-bit signed integer |
Uint32Array | 32-bit unsigned integer |
Float32Array | 32-bit IEEE754 floating point number |
Float64Array | 64-bit IEEE754 floating point number |
The example below creates a new ArrayBuffer from scratch and interprets its contents in a few different ways:
// Create an 8 byte buffervar buffer = new ArrayBuffer(8);
// View as an array of Uint8s and put 0x05 in each bytevar uint8s = new Uint8Array(buffer);for (var i = 0; i < 8; i++) {uint8s[i] = 5; // fill each byte with 0x05}
// Inspect the resulting arrayuint8s[0] === 5; // true - each byte has value 5uint8s.byteLength === 8; // true - there are 8 Uint8s
// View the same buffer as an array of Uint32s var uint32s = new Uint32Array(buffer);
// The same raw bytes are now interpreted differentlyuint32s[0] === 84215045 // true - 0x05050505 == 84215045
In this way, Typed Arrays can be used for tasks such as creating floating point values from their byte-level components or for building data structures that require a very specific layout of data for efficiency or interoperation.
Комментариев нет:
Отправить комментарий