JavaScript - The TypedArray Object

Hello there, future coding superstars! ? Today, we're going to embark on an exciting journey into the world of TypedArrays in JavaScript. Don't worry if you're new to programming - I'll be your friendly guide, and we'll take this step by step. So, grab your favorite beverage, get comfy, and let's dive in!

JavaScript - TypedArray

What is a TypedArray?

Imagine you're organizing a big party (because who doesn't love a good party, right?). You need to keep track of how many cups, plates, and utensils you have. That's kind of what a TypedArray does in JavaScript - it helps us organize and store specific types of data efficiently.

A TypedArray is a special kind of array in JavaScript that can only contain numbers of a specific type. It's like having separate boxes for your forks, spoons, and knives instead of throwing them all in one big drawer.

// Creating a TypedArray of 8-bit integers
const myArray = new Int8Array(5);
console.log(myArray); // Output: Int8Array(5) [0, 0, 0, 0, 0]

In this example, we've created a TypedArray that can hold five 8-bit integers. It's like setting up five small boxes, each able to hold a number between -128 and 127.

Why TypedArray?

You might be wondering, "Why bother with TypedArrays when we have regular arrays?" Great question! TypedArrays have some superpowers that make them perfect for certain situations:

  1. Speed: They're faster for numerical operations.
  2. Memory efficiency: They use a fixed amount of memory.
  3. Compatibility: They play well with binary data and other languages.

It's like using a specialized tool instead of a Swiss Army knife - sometimes, you need that perfect fit!

TypedArray Objects

JavaScript offers various types of TypedArrays, each designed for different number types and sizes. Let's look at them in a nice, organized table:

TypedArray Description Range
Int8Array 8-bit signed integer -128 to 127
Uint8Array 8-bit unsigned integer 0 to 255
Int16Array 16-bit signed integer -32,768 to 32,767
Uint16Array 16-bit unsigned integer 0 to 65,535
Int32Array 32-bit signed integer -2,147,483,648 to 2,147,483,647
Uint32Array 32-bit unsigned integer 0 to 4,294,967,295
Float32Array 32-bit floating point ~1.2E-38 to ~3.4E+38
Float64Array 64-bit floating point ~5.0E-324 to ~1.8E+308

Wow, that's quite a list! Don't worry if it seems overwhelming - we'll use examples to make it all clear.

TypedArray Properties

TypedArrays come with some handy properties. Let's explore them:

1. length

This tells us how many elements are in our TypedArray.

const myArray = new Int16Array(3);
console.log(myArray.length); // Output: 3

2. BYTES_PER_ELEMENT

This property tells us how many bytes each element in the array takes up.

console.log(Int8Array.BYTES_PER_ELEMENT); // Output: 1
console.log(Int16Array.BYTES_PER_ELEMENT); // Output: 2

It's like knowing how big each box is in our storage system!

TypedArray Static Methods

TypedArrays come with some built-in methods that we can use without creating an instance. Let's look at a couple:

1. TypedArray.from()

This method creates a new TypedArray from an array-like object.

const regularArray = [1, 2, 3, 4];
const typedArray = Int8Array.from(regularArray);
console.log(typedArray); // Output: Int8Array(4) [1, 2, 3, 4]

It's like converting our mixed utensil drawer into neatly organized boxes!

2. TypedArray.of()

This method creates a new TypedArray with a variable number of arguments.

const myArray = Int16Array.of(1, 2, 3, 4, 5);
console.log(myArray); // Output: Int16Array(5) [1, 2, 3, 4, 5]

It's like saying, "Here are the items, please organize them for me!"

TypedArray Instance Methods

Now, let's look at some methods we can use on our TypedArray instances:

1. set()

This method lets us copy values into our TypedArray.

const myArray = new Int8Array(5);
myArray.set([1, 2, 3]);
console.log(myArray); // Output: Int8Array(5) [1, 2, 3, 0, 0]

It's like putting items into our organized boxes.

2. subarray()

This method returns a new TypedArray that's a portion of the original.

const originalArray = new Int8Array([1, 2, 3, 4, 5]);
const subArray = originalArray.subarray(1, 4);
console.log(subArray); // Output: Int8Array(3) [2, 3, 4]

It's like taking a few boxes out of our storage system for a specific task.

Examples

Let's put all this knowledge together with some practical examples!

Example 1: Creating and Modifying a TypedArray

// Create a TypedArray of 8-bit unsigned integers
const pixelData = new Uint8Array(4);

// Set RGB values for a pixel (Red: 255, Green: 128, Blue: 64, Alpha: 255)
pixelData[0] = 255; // Red
pixelData[1] = 128; // Green
pixelData[2] = 64;  // Blue
pixelData[3] = 255; // Alpha (fully opaque)

console.log(pixelData); // Output: Uint8Array(4) [255, 128, 64, 255]

In this example, we're using a Uint8Array to represent the color values of a pixel. Each value is between 0 and 255, perfect for 8-bit unsigned integers!

Example 2: Using TypedArrays for Performance

const size = 1000000;

// Using regular array
console.time('Regular Array');
const regularArray = new Array(size);
for (let i = 0; i < size; i++) {
regularArray[i] = i;
}
console.timeEnd('Regular Array');

// Using TypedArray
console.time('TypedArray');
const typedArray = new Int32Array(size);
for (let i = 0; i < size; i++) {
typedArray[i] = i;
}
console.timeEnd('TypedArray');

Run this code, and you'll likely see that the TypedArray is faster! It's like having a well-organized storage system versus throwing everything into a big pile.

And there you have it, folks! We've journeyed through the land of TypedArrays, from understanding what they are to seeing them in action. Remember, practice makes perfect, so don't be afraid to experiment with these concepts.

Before you know it, you'll be TypedArray wizards, optimizing your code and impressing your fellow developers. Until next time, happy coding! ??‍??‍?

以下是繁體中文的翻譯:

JavaScript - TypedArray 物件

你好,未來的編程超新星!? 今天,我們將踏上一段令人興奮的旅程,探索 JavaScript 中的 TypedArrays。如果你是編程新手,別擔心——我會成為你的友好導遊,我們會一步步來。所以,拿起你喜歡的飲料,放鬆身心,讓我們一起深入探究吧!

TypedArray 是什麼?

想像一下你在籌備一個大型派對(因為誰不喜歡一個好的派對呢?)。你需要記錄有多少個杯子、盤子、餐具等。在 JavaScript 中,TypedArray 就有點像這樣——它幫助我們有效地組織和存儲特定類型的數據。

TypedArray 是 JavaScript 中一種特殊的數組,只能包含特定類型的數字。這就像為你的餐叉、湯匙和刀子分別準備不同的盒子,而不是把所有東西都扔進一個大抽屜。

// 創建一個包含 8 位整數的 TypedArray
const myArray = new Int8Array(5);
console.log(myArray); // 輸出: Int8Array(5) [0, 0, 0, 0, 0]

在這個例子中,我們創建了一個可以存放五個 8 位整數的 TypedArray。這就像設置五個小盒子,每個盒子能夠存放從 -128 到 127 的數字。

為什麼使用 TypedArray?

你可能會想,"我們有普通數組,為什麼還要麻煩使用 TypedArrays 呢?" 好問題!TypedArrays 有一些超能力,讓它在某些情況下成為完美選擇:

  1. 速度:它們在數字運算上更快。
  2. 記憶體效率:它們使用固定的記憶體。
  3. 兼容性:它們與二進制數據和其他語言配合得很好。

這就像使用專業工具而不是瑞士軍刀——有時候,你需要那個完美的配合!

TypedArray 物件

JavaScript 提供了各種類型的 TypedArrays,每種都設計用於不同的數字類型和大小。讓我們來看看它們,並以一個整齊的表格來展示:

TypedArray 描述 範圍
Int8Array 8 位有符號整數 -128 到 127
Uint8Array 8 位無符號整數 0 到 255
Int16Array 16 位有符號整數 -32,768 到 32,767
Uint16Array 16 位無符號整數 0 到 65,535
Int32Array 32 位有符號整數 -2,147,483,648 到 2,147,483,647
Uint32Array 32 位無符號整數 0 到 4,294,967,295
Float32Array 32 位浮點數 大約 1.2E-38 到 3.4E+38
Float64Array 64 位浮點數 大約 5.0E-324 到 1.8E+308

哇,這是一個長長的列表!如果這讓你感到不知所措,別擔心——我們會用例子來讓這些概念變得清晰。

TypedArray 屬性

TypedArrays 伴有一些方便的屬性。讓我們來探索它們:

1. length

這告訴我們 TypedArray 中有多少個元素。

const myArray = new Int16Array(3);
console.log(myArray.length); // 輸出: 3

2. BYTES_PER_ELEMENT

這個屬性告訴我們數組中的每個元素佔用多少個字節。

console.log(Int8Array.BYTES_PER_ELEMENT); // 輸出: 1
console.log(Int16Array.BYTES_PER_ELEMENT); // 輸出: 2

這就像知道我們存儲系統中每個盒子有多大!

TypedArray 靜態方法

TypedArrays 提供了一些我們可以在不創建實例的情況下使用的方法。讓我們看兩個:

1. TypedArray.from()

這個方法從類數組對象創建一個新的 TypedArray。

const regularArray = [1, 2, 3, 4];
const typedArray = Int8Array.from(regularArray);
console.log(typedArray); // 輸出: Int8Array(4) [1, 2, 3, 4]

這就像把我們混亂的餐具抽屜轉變成整齊的盒子!

2. TypedArray.of()

這個方法使用可變數量的參數創建一個新的 TypedArray。

const myArray = Int16Array.of(1, 2, 3, 4, 5);
console.log(myArray); // 輸出: Int16Array(5) [1, 2, 3, 4, 5]

這就像說,"這裡有一些物品,請為我組織它們!"

TypedArray 實例方法

現在,讓我們看看我們可以在 TypedArray 實例上使用的一些方法:

1. set()

這個方法讓我們將值複製到我們的 TypedArray 中。

const myArray = new Int8Array(5);
myArray.set([1, 2, 3]);
console.log(myArray); // 輸出: Int8Array(5) [1, 2, 3, 0, 0]

這就像把我們的物品放到組織好的盒子中。

2. subarray()

這個方法返回一個新的 TypedArray,它是原始數組的一部分。

const originalArray = new Int8Array([1, 2, 3, 4, 5]);
const subArray = originalArray.subarray(1, 4);
console.log(subArray); // 輸出: Int8Array(3) [2, 3, 4]

這就像從我們的存儲系統中取出一些盒子,為特定任務使用。

示例

讓我們把所有的知識一起用一些實際的例子來展示!

示例 1:創建和修改 TypedArray

// 創建一個包含 8 位無符號整數的 TypedArray
const pixelData = new Uint8Array(4);

// 設置像素的 RGB 值(紅色: 255,綠色: 128,藍色: 64,透明度: 255)
pixelData[0] = 255; // 紅色
pixelData[1] = 128; // 綠色
pixelData[2] = 64;  // 藍色
pixelData[3] = 255; // 透明度(完全不透明)

console.log(pixelData); // 輸出: Uint8Array(4) [255, 128, 64, 255]

在這個例子中,我們使用 Uint8Array 來表示像素的顏色值。每個值都在 0 到 255 之間,這對於 8 位無符號整數來說是完美的!

示例 2:使用 TypedArrays 提高性能

const size = 1000000;

// 使用普通數組
console.time('Regular Array');
const regularArray = new Array(size);
for (let i = 0; i < size; i++) {
regularArray[i] = i;
}
console.timeEnd('Regular Array');

// 使用 TypedArray
console.time('TypedArray');
const typedArray = new Int32Array(size);
for (let i = 0; i < size; i++) {
typedArray[i] = i;
}
console.timeEnd('TypedArray');

運行這段代碼,你很可能會看到 TypedArray 更快!這就像擁有一個組織良好的存儲系統,而不是把所有東西都扔進一堆。

好了,各位!我們已經穿越了 TypedArrays 的領土,從理解它們是什麼到看到它們在實際動作中的表現。記住,實踐使人完美,所以不要害怕嘗試這些概念。

在你意識到之前,你會成為 TypedArray 的魔法師,優化你的代碼,讓你的開發夥伴印象深刻。下次見,快樂編程!??‍??‍?

Credits: Image by storyset