What is ArrayBuffer
The ArrayBuffer object is used to represent a universal, fixed-length raw binary data buffer.
It is a byte array, usually called "byte array" in other languages.
You can't directly manipulate the contents of the ArrayBuffer, but use typed array objects or DataView objects, which will represent the data in the buffer in a specific format, and read and write the contents of the buffer through these formats.
Simple usage
const buffer = new ArrayBuffer(8);
console.log(buffer.byteLength); // 8
length is greater than Number.MAX_SAFE_INTEGER (>= 2 53) or a negative number, a RangeError exception will be thrown. **
effect
A large number of byte streams are read from XHR, File API, Canvas, WebGL, etc., if you use Array in JS to store it, it is wasteful and inefficient
So in order to cooperate with these new APIs to enhance the binary processing capabilities of JS, there is ArrayBuffer
When creating an ArrayBuffer, it is equivalent to applying for a piece of memory, and it is not (and not convenient) to use it directly
So there is also TypedArray, such as Uint32Array, Int16Array, Int8Array, Float32Array, etc.
These are the specific implementations used to manipulate TypedArray
TypeArray
A TypedArray object describes an array-like view of the underlying binary data buffer. In fact, there is no global property named TypedArray, and there is no constructor named TypedArray. Instead, there are many different global properties whose values are typed array constructors for specific element types, as shown below
// 下面代码是语法格式,不能直接运行,
// TypedArray 关键字需要替换为底部列出的构造函数。
new TypedArray(); // ES2017中新增
new TypedArray(length);
new TypedArray(typedArray);
new TypedArray(object);
new TypedArray(buffer [, byteOffset [, length]]);
// TypedArray 指的是以下的其中之一:
Int8Array();
Uint8Array();
Uint8ClampedArray();
Int16Array();
Uint16Array();
Int32Array();
Uint32Array();
Float32Array();
Float64Array();
- Unit8Array refers to treating each byte (8-bit) of ArrayBuffer as a single unsigned integer number (0-255)
- Unit16Array is represented as an array using 16 bits (2 bytes) to represent an unsigned integer (0 ~ 2^16-1)
- Int8Array means using 8 bits to represent a signed integer (-128 ~ 127)
- Float32Array means using 32 bits to represent a floating point number
- Unit7ClampedArray is the same as Unit8Array in the range of 0 to 255, and the processing of out-of-range is different, which is related to image processing (generally the pixel range is also 0 to 255)
scenes to be used:
File conversion:
arrayBuffer can be converted to Blob object:
const blob = new Blob([arrayBuffer],{type:"xxx/xxx"});
Convert Blob to arrayBuffer:
const fileReader:FileReader = new FileReader();
fileReader.addEventListener("load",(event)=>{
const arrayBuffer = event.target.result;
//...
})
fileReader.readAsArrayBuffer(file);
or:
const arrayBuffer = await file.arrayBuffer();
Get it from ajax:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'xxxxx');
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
const arrayBuffer = xhr.response;
}
};
xhr.send();
Example 1
A certain way of playing audio
const audioContext = new AudioContext();
const buffer = await file.arrayBuffer();
const auidoBuffer = await audioContext.decodeAudioData(buffer);
const source = audioContext.createBufferSource();
source.buffer = auidoBuffer;
source.connect(audioContext.destination);
source.start();
Example 2
Read binary file
// HTML 代码如下
// <input type="file" onchange="typefile(this.files[0])"></input>
function typefile(file) {
// 文件开头的四个字节,生成一个 Blob 对象
let slice = file.slice(0, 4);
let reader = new FileReader();
// 读取这四个字节
reader.readAsArrayBuffer(slice);
reader.onload = function (e) {
let buffer = reader.result;
// 将这四个字节的内容,视作一个32位整数
let view = new DataView(buffer);
let magic = view.getUint32(0, false);
// 根据文件的前四个字节,判断它的类型
switch(magic) {
case 0x89504E47: file.verified_type = 'image/png'; break;
case 0x47494638: file.verified_type = 'image/gif'; break;
case 0x25504446: file.verified_type = 'application/pdf'; break;
case 0x504b0304: file.verified_type = 'application/zip'; break;
}
console.log(file.name, file.verified_type);
};
}
Summarize
There are still a lot of things that are not SharedArrayBuffers
here, such as 061a64a92f2cca, big and small problems, etc., if you want to go deeper, you can understand it yourself
The use of buffer in the front-end scene is indeed very rare, but it will be seen when it comes to the lower level or a little bit of the side.At this time, we also require us to understand him, such as file, canvas, WebGL, WASM, EXCEL processing
Quote
- https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
- https://www.zhihu.com/question/30401979?sort=created
- https://javascript.info/arraybuffer-binary-arrays
- https://zhuanlan.zhihu.com/p/376721544
- https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
- https://zhuanlan.zhihu.com/p/225286934
- https://zhuanlan.zhihu.com/p/97711340
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。