15 Aralık 2021
Bu materyal sadece Čeština, English, Español, فارسی, Français, Italiano, 日本語, 한국어, Русский, Українська, Oʻzbek, 简体中文 dillerinde mevcuttur. Lütfen Türkçe diline çevirmek için bize yardım edin.

ArrayBuffer, binary arrays

In web-development we meet binary data mostly while dealing with files (create, upload, download). Another typical use case is image processing.

That’s all possible in JavaScript, and binary operations are high-performant.

Although, there’s a bit of confusion, because there are many classes. To name a few:

  • ArrayBuffer, Uint8Array, DataView, Blob, File, etc.

Binary data in JavaScript is implemented in a non-standard way, compared to other languages. But when we sort things out, everything becomes fairly simple.

The basic binary object is ArrayBuffer – a reference to a fixed-length contiguous memory area.

We create it like this:

let buffer = new ArrayBuffer(16); // create a buffer of length 16
alert(buffer.byteLength); // 16

This allocates a contiguous memory area of 16 bytes and pre-fills it with zeroes.

ArrayBuffer is not an array of something

Let’s eliminate a possible source of confusion. ArrayBuffer has nothing in common with Array:

  • It has a fixed length, we can’t increase or decrease it.
  • It takes exactly that much space in the memory.
  • To access individual bytes, another “view” object is needed, not buffer[index].

ArrayBuffer is a memory area. What’s stored in it? It has no clue. Just a raw sequence of bytes.

To manipulate an ArrayBuffer, we need to use a “view” object.

A view object does not store anything on it’s own. It’s the “eyeglasses” that give an interpretation of the bytes stored in the ArrayBuffer.

For instance:

  • Uint8Array – treats each byte in ArrayBuffer as a separate number, with possible values are from 0 to 255 (a byte is 8-bit, so it can hold only that much). Such value is called a “8-bit unsigned integer”.