First, the concept
The binary array consists of the Arraybuffer object Typearray view and the DataView view, which is an interface for JavaScript to manipulate binary data.
It was released as early as February 2011, but due to the advent of ES6, some new methods have been added to these objects. It is a mechanism similar to the direct manipulation of bytes in C language.
Create a background
The original design purpose of this interface is related to the WEBGL project. The so-called WebGL refers to the communication interface between the browser and the video card, in order to satisfy the large number of JavaScript and
Real-time data exchange between them must be binary, not traditional text format. Text format to pass a 32-bit integer, both ends of the JavaScript script and the video card are formatted to convert, it will be very time-consuming.
At this point, if there is a mechanism, like the C language, directly manipulate the byte, the 4-byte 32-bit integer, in binary form into the video card intact, the performance of the script will be greatly improved.
It is much like a C-language array, allowing developers to manipulate memory directly in the form of array subscripts, greatly enhancing JavaScript's ability to process binary data, making it possible for developers to communicate binary with JavaScript's native interface to the operating system.
Second,ArrayBuffer object: Represents the original binary data. Operations can be performed via Typearray, i.e., memory can be manipulated
It can not read and write directly, only through ( TypedArray
and DataView
) to read and write.
ArrayBuffer
is also a constructor that can allocate a contiguous area of memory that can hold data.
For example, I want to generate a 32-byte memory area where the value of each byte is 0 by default and can be created like this:
var buffer32 = new ArrayBuffer(32);
var buffer = new ArrayBuffer();
console.log(buf);
如所示:
ArrayBuffer 的实力上 有一个 byteLength的属性,原型上有一个slice方法,还有共有方法 isView 下面我们来给大家一一解读
byteLength
:是ArrayBuffer
实例的属性,返回所分配的内存区域的字节长度。
需要注意的是:如果你想分配一块比较大的内存区域,需要检查是否分配成功,因为可能没有那么多的连续空余内存。
if(buffer.byteLength === n){ //成功}else{ //失败}
slice
: There are two parameters, the first parameter represents the byte ordinal (containing this byte) that starts the copy, the second parameter represents the byte ordinal of the cutoff copy (excluding this byte), and if the second argument is omitted, the default cutoff is to the ArrayBuffer
end of the original object.
slice
: Is ArrayBuffer
a method of an instance that allows a copy of a part of the memory area to be generated to generate a new ArrayBuffer
object.
var buffer = new ArrayBuffer (8);
var newbuffer = buffer.slice (0, 3);
Console.log (buffer); {Bytelength:8}
Console.log (Newbuffer);//{Bytelength:3}
Arraybuffer.isview ()
isView
: Is ArrayBuffer
a static method that returns a Boolean value that indicates whether the argument is a ArrayBuffer
view instance. This method is roughly equivalent to judging the parameter, whether it is an TypedArray
instance or an DataView
instance.
var buffer = new ArrayBuffer(8);ArrayBuffer.isView(buffer) // falsevar v = new Int32Array(buffer);ArrayBuffer.isView(v) // true
three. TypedArray View
The Typedarray array provides only 9 fixed constructors that are used to generate an array instance of the corresponding type.
(1) TypedArray (buffer, byteoffset=0, length?)
A view's constructor can accept three parameters:
First parameter (required): the underlying object that corresponds to the view ArrayBuffer
.
Second parameter (optional): The byte ordinal at which the view begins, starting from 0 by default.
Third parameter (optional): The view contains the number of data, by default, until the end of this section of memory area.
Create a 8-byte arraybuffervar b = new ArrayBuffer (8); Create a Int32 view that points to B, starting at byte 0 until the end of the buffer var v1 = new Int32array (b);//[0, 0] not very understanding //Creating a Uint8 view pointing to B , starting at byte 2 until the end of the buffer var v2 = new Uint8array (b, 2);//[0, 0, 0, 0, 0, 0]//Create a Int16 view that points to B, starting at byte 2, length 2 var v3 = new Int16array (b, 2, 2);//
[0, 0]
V1[0] is a 32-bit integer that points to byte 0~ byte 3;v2[0] is a 8-bit unsigned integer that points to byte 2;v3[0] is a 16-bit integer that points to byte 2~ byte 3. As long as any one view changes memory, it will be reflected on the other two views.
Note: The byteoffset must be consistent with the type of data being created, such as: A signed 16-bit integer requires two bytes, so the Byteoffset parameter must be divisible by 2
(2) TypedArray (length)
Views can also be ArrayBuffer
generated without directly allocating memory through the object.
var f64a = new Float64Array(8); //64字节f64a[0] = 10;f64a[1] = 20;f64a[2] = f64a[0] + f64a[1]; // 30
(3) TypedArray (TypedArray)
TypedArray
An array of constructors that can accept another TypedArray
instance as a parameter.
var typedArray = new Int8Array(new Uint8Array(4));
Note: The new array will open up a new memory storage data.
var x =NewInt8array ([1,1]);var y =NewInt8array (x); x[0] //1y[0] //1x[0] = 2;y[0] //1//based on the same memory var x = New int8array ([1 , 1]); var y = new int8array (x.buffer), x[0] //1y[0] //1x[0] = 2;y[0] // 2
(4) TypedArray (Arraylikeobject)
//普通数组生成TypedArray实例var typedArray = new Uint8Array([1, 2, 3, 4]);//这时TypedArray视图会重新开辟内存,不会在原数组的内存上建立视图//TypedArray数组转换回普通数组var normalArray = Array.prototype.slice.call(typedArray);
It is important to note that the Typedarray array has all the operation methods and properties of the normal array in addition to the Concat method.
If you want to merge multiple Typedarray arrays, you can use the following function.
functionCONCATENATE (Resultconstructor, ... arrays) {Let Totallength = 0; for (let arr of arrays) { Totallength + = Arr.length; } let result = new resultconstructor (totallength); let offset = 0; for (let arr of arrays) { Result.set (arr, offset); Offset + = Arr.length; } return result;} Concatenate (uint8array, uint8array.of ( 1, 2), uint8array.of (3, 4)) //Uint8array [1, 2, 3, 4]
Typedarray arrays can also be traversed.
let ui8 = Uint8Array.of(0, 1, 2);for (let byte of ui8) { console.log(byte);}// 0// 1// 2
ArrayBuffer and the conversion of strings to each other
Note: The encoding method of the string is determined before it can be converted to each other.
Arraybuffer to string, argument to Arraybuffer objectfunctionAB2STR (BUF) {ReturnString.fromCharCode.apply (NULL, new Uint16array (BUF));} the//string is converted to a ArrayBuffer object, and the argument is string function str2ab (str) { var buf = new ArrayBuffer (Str.length * C11>2); //Each character occupies 2 bytes of var bufview = new uint16array (BUF); for (var i = 0, strLen = str.length; i < StrLen; i++) {Bufview[i] = str.charcodeat (i);} return buf;}
TypedArray.prototype.buffer
: Returns the Arraybuffer object for the entire memory area, with the property read-only.
TypedArray.prototype.byteLength
: Returns the length of memory occupied by the Typedarray array, in bytes, and the property is read-only.
TypedArray.prototype.byteOffset
: Returns the Typedarray array starting from which byte of the underlying Arraybuffer object and the property is read-only.
TypedArray.prototype.length
: How many Members the Typedarray array contains.
TypedArray.prototype.set()
: Used to copy an array (an ordinary array or an Typedarray array).
TypedArray.prototype.subarray()
: For a part of the Typedarray array, create a new view.
TypedArray.prototype.slice()
: Returns a new Typedarray instance at the specified location.
TypedArray.of()
: Used to convert a parameter to a Typedarray instance.
TypedArray.from()
: Returns a Typedarray instance based on this structure.
3. Composite View
var buffer = new ArrayBuffer(24);var idView = new Uint32Array(buffer, 0, 1);var usernameView = new Uint8Array(buffer, 4, 16);var amountDueView = new Float32Array(buffer, 20, 1);
The above code divides a 24-byte-length Arraybuffer object into three pieces:
byte 0 to byte 3: A 32-bit unsigned integer
Byte 4 to byte 19:16 8-bit integer
byte 20 to byte 23:1 32-bit floating-point number
4. DataView View
DataView
An instance has the following properties, meaning the TypedArray
same method as the instance.
DataView.prototype.buffer: Returns the corresponding Arraybuffer object
DataView.prototype.byteLength: Returns the occupied memory byte length
DataView.prototype.byteOffset: Returns the current view from which byte of the corresponding Arraybuffer object begins
DataView
The instance provides 8 methods of reading memory.
GetInt8: Reads 1 bytes and returns a 8-bit integer.
GetUint8: Reads 1 bytes and returns an unsigned 8-bit integer.
GetInt16: Reads 2 bytes and returns a 16-bit integer.
GetUint16: Reads 2 bytes and returns an unsigned 16-bit integer.
GetInt32: Reads 4 bytes and returns a 32-bit integer.
GetUint32: Reads 4 bytes and returns an unsigned 32-bit integer.
GetFloat32: Reads 4 bytes and returns a 32-bit floating-point number.
GetFloat64: Reads 8 bytes and returns a 64-bit floating-point number.
DataView
The view provides 8 methods of writing memory.
SetInt8: Writes a 1-byte 8-bit integer.
SetUint8: Writes a 1-byte, 8-bit unsigned integer.
SetInt16: Writes a 2-byte 16-bit integer.
SetUint16: Writes a 2-byte, 16-bit unsigned integer.
SetInt32: Writes a 4-byte 32-bit integer.
SetUint32: Writes a 4-byte, 32-bit unsigned integer.
SetFloat32: Writes a 4-byte 32-bit floating-point number.
SetFloat64: Writes a 8-byte 64-bit floating-point number.
ES6 Binary Arrays-basics