Computer >> Computer tutorials >  >> Programming >> Javascript

Javascript typed arrays


JavaScript typed arrays are array-like objects and provide a mechanism for accessing raw binary data.

Array objects grow and shrink dynamically and can have any JavaScript value. JavaScript engines perform optimizations so that these arrays are fast.

Note − typed arrays are not to be confused with normal arrays, as calling Array.isArray() on a typed array returns false. Moreover, not all methods available for normal arrays are supported by typed arrays

JavaScript typed arrays are implemented using buffers and views.

A buffer is an object representing a chunk of data; it has no format to speak of and offers no mechanism for accessing its contents.

In order to access the memory contained in a buffer, you need to use a view. A view provides a data type, starting offset, and the number of elements — that turns the data into a typed array.

Example

// create a buffer with a fixed length of 16-bytes
let buffer = new ArrayBuffer(16);
// Before we can really work with this buffer, we need to create a view.
// Let's create a view that treats the data in the buffer as an array of 32-bit signed integers:
let int32View = new Int32Array(buffer);
// we can access the fields in the array just like a normal array
for (let i = 0; i < int32View.length; i++) {
   int32View[i] = i * 2;
}
console.log(int32View);

Output

Int32Array { [Iterator] 0: 0, 1: 2, 2: 4, 3: 6 }