Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Có Boolean Typed Array trong JavaScript không?

Không, JavaScript không có Boolean Typed Array.

Các Typed Array có sẵn (chỉ số nguyên và float):

Typed ArrayKích thướcMô tảPhạm vi
Int8Array1 byteSigned integer-128 ~ 127
Uint8Array1 byteUnsigned integer0 ~ 255
Uint8ClampedArray1 byteUnsigned, clamp 0-2550 ~ 255 (clamp)
Int16Array2 bytesSigned integer-32,768 ~ 32,767
Uint16Array2 bytesUnsigned integer0 ~ 65,535
Int32Array4 bytesSigned integer-2,147,483,648 ~ 2,147,483,647
Uint32Array4 bytesUnsigned integer0 ~ 4,294,967,295
Float32Array4 bytesIEEE 754 float±3.4e38
Float64Array8 bytesIEEE 754 double±1.8e308
BigInt64Array8 bytesBigInt signed±2^63-1
BigUint64Array8 bytesBigInt unsigned0 ~ 2^64-1

Giải pháp thay thế cho Boolean Array:

1. Uint8Array (0/1) — Tiết kiệm bộ nhớ nhất

const boolArr = new Uint8Array(100); // 100 bytes
boolArr[0] = 1; // true
boolArr[1] = 0; // false
// Chuyển về boolean: Boolean(boolArr[0])

2. BitArray / Bitset (1 bit/giá trị) — Tối ưu nhất

class BitArray {
    constructor(size) {
        this.words = new Uint32Array(Math.ceil(size / 32));
    }
    set(index, value) {
        const word = index >> 5;
        const bit = index & 31;
        if (value) this.words[word] |= (1 << bit);
        else this.words[word] &= ~(1 << bit);
    }
    get(index) {
        const word = index >> 5;
        const bit = index & 31;
        return !!(this.words[word] & (1 << bit));
    }
}

3. Uint8Array + view (cho WebGL, WASM)

// Buffer chia sẻ
const buffer = new ArrayBuffer(100);
const boolView = new Uint8Array(buffer);
const intView = new Int32Array(buffer);

4. Thường dùng: Array thường

const flags = [true, false, true]; // Đủ nhanh cho hầu hết trường hợp

Khuyến nghị: Dùng mảng thường [] cho code đơn giản. Dùng Uint8Array hoặc BitArray cho dữ liệu lớn (hình ảnh, game, scientific computing).