阿里云主机折上折
  • 微信号
Current Site:Index > Extension of binary arrays

Extension of binary arrays

Author:Chuan Chen 阅读数:30264人阅读 分类: JavaScript

ECMAScript 6 significantly expanded binary arrays by introducing new APIs for ArrayBuffer, TypedArray, and DataView, enhancing the ability to handle binary data. These features provide more efficient tools for scenarios such as file operations, network communication, and graphics processing.

Enhancements to ArrayBuffer

ES6 optimized the ArrayBuffer constructor and added the ArrayBuffer.isView() method to determine whether an object is an instance of TypedArray or DataView:

const buffer = new ArrayBuffer(16);
const int32View = new Int32Array(buffer);

console.log(ArrayBuffer.isView(int32View)); // true
console.log(ArrayBuffer.isView(buffer));    // false

The ArrayBuffer.prototype.slice() method now supports creating copies of partial data:

const buffer1 = new ArrayBuffer(8);
const buffer2 = buffer1.slice(4, 8);

New Features of TypedArray

ES6 standardized the behavior of TypedArray constructors and added various static and instance methods:

Static Methods

The TypedArray.from() method can create typed arrays from array-like or iterable objects:

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

The TypedArray.of() method can create typed arrays with a variable number of arguments:

const floats = Float32Array.of(1.1, 2.2, 3.3);
console.log(floats); // Float32Array [1.1, 2.2, 3.3]

Instance Methods

The new set() method supports setting values starting from a specified offset:

const arr1 = new Uint8Array(8);
const arr2 = new Uint8Array([1, 2, 3]);
arr1.set(arr2, 2);
console.log(arr1); // Uint8Array [0, 0, 1, 2, 3, 0, 0, 0]

The subarray() method can create new views based on the same buffer:

const source = new Int16Array([1, 2, 3, 4, 5]);
const sub = source.subarray(1, 3);
console.log(sub); // Int16Array [2, 3]

Extensions to DataView

The DataView object added support for more data types:

const buffer = new ArrayBuffer(16);
const view = new DataView(buffer);

view.setInt16(0, 32767);  // Maximum 16-bit signed integer
view.setBigInt64(8, 9007199254740991n); // 64-bit big integer

Iteration Over Binary Arrays

ES6 made TypedArray iterable, allowing direct use of for...of loops:

const uint8 = new Uint8Array([10, 20, 30]);
for (const value of uint8) {
  console.log(value); // Outputs 10, 20, 30 in sequence
}

New iterator methods entries(), keys(), and values() were also added:

const arr = new Uint8Array([1, 2, 3]);
const iter = arr.entries();

for (const [index, value] of iter) {
  console.log(index, value); // 0 1, 1 2, 2 3
}

Conversion Between Binary Arrays and Strings

New TextEncoder and TextDecoder APIs enable conversion between strings and binary data:

const encoder = new TextEncoder();
const encoded = encoder.encode("Hello");
console.log(encoded); // Uint8Array [72, 101, 108, 108, 111]

const decoder = new TextDecoder();
const str = decoder.decode(encoded);
console.log(str); // "Hello"

Copying and Filling Binary Arrays

The TypedArray.prototype.copyWithin() method can copy data within an array:

const arr = new Uint8Array([1, 2, 3, 4, 5]);
arr.copyWithin(0, 3, 5);
console.log(arr); // Uint8Array [4, 5, 3, 4, 5]

The TypedArray.prototype.fill() method can fill an array:

const arr = new Uint8Array(4).fill(255);
console.log(arr); // Uint8Array [255, 255, 255, 255]

Searching in Binary Arrays

New methods includes(), indexOf(), and lastIndexOf() were added:

const arr = new Int8Array([1, 2, 3, 2, 1]);
console.log(arr.includes(3));      // true
console.log(arr.indexOf(2));       // 1
console.log(arr.lastIndexOf(2));   // 3

Sorting Binary Arrays

TypedArray now supports the sort() method:

const arr = new Int8Array([5, 3, 4, 1, 2]);
arr.sort();
console.log(arr); // Int8Array [1, 2, 3, 4, 5]

A custom comparison function can be passed for sorting:

const arr = new Float32Array([1.5, 2.5, 1.0, 3.5]);
arr.sort((a, b) => b - a); // Sort in descending order
console.log(arr); // Float32Array [3.5, 2.5, 1.5, 1.0]

Merging Binary Arrays

TypedArray added the static method TypedArray.prototype.concat():

const arr1 = new Uint8Array([1, 2]);
const arr2 = new Uint8Array([3, 4]);
const combined = new Uint8Array([...arr1, ...arr2]);
console.log(combined); // Uint8Array [1, 2, 3, 4]

Buffer Operations for Binary Arrays

The proposed ArrayBuffer.transfer() method can resize buffers:

// Proposed API; check browser support before use
const buffer1 = new ArrayBuffer(8);
const buffer2 = ArrayBuffer.transfer(buffer1, 16);
console.log(buffer2.byteLength); // 16

Binary Arrays and Regular Expressions

TypedArray can be used with regular expressions:

const binaryData = new Uint8Array([72, 101, 108, 108, 111]);
const text = new TextDecoder().decode(binaryData);
console.log(/Hello/.test(text)); // true

Performance Optimization with Binary Arrays

Using TypedArray for large datasets is significantly faster than regular arrays:

// Create arrays with 1 million elements
const length = 1e6;
const normalArray = new Array(length).fill(0);
const typedArray = new Float64Array(length);

// Performance test
console.time('Normal Array');
normalArray.map(x => x * 2);
console.timeEnd('Normal Array');

console.time('Typed Array');
typedArray.map(x => x * 2);
console.timeEnd('Typed Array');

Integration with Web APIs

Modern browser APIs widely use TypedArray:

// Get image data from Canvas
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const uint8Array = imageData.data; // Uint8ClampedArray

// Send binary data via WebSocket
const socket = new WebSocket('ws://example.com');
socket.binaryType = 'arraybuffer';
socket.send(new Uint8Array([1, 2, 3]).buffer);

Shared Memory with Binary Arrays

SharedArrayBuffer allows memory sharing between multiple Worker threads:

// Main thread
const sharedBuffer = new SharedArrayBuffer(1024);
const worker = new Worker('worker.js');
worker.postMessage({ buffer: sharedBuffer });

// worker.js
self.onmessage = function(e) {
  const sharedArray = new Uint32Array(e.data.buffer);
  Atomics.add(sharedArray, 0, 1); // Atomic operation
};

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:正则表达式的扩展

下一篇:国际化API

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.