数组类型
JavaScript Provides 8 Typed Array types:
JavaScript提供8种类型数组类型:
Int8Array
an array of 8-bit signed integersInt8Array
一个8位有符号整数的数组Int16Array
an array of 16-bit signed integersInt16Array
16位有符号整数的数组Int32Array
an array of 32-bit signed integersInt32Array
32位有符号整数的数组Uint8Array
an array of 8-bit unsigned integersUint8Array
8位无符号整数的数组Uint16Array
an array of 16-bit unsigned integersUint16Array
16位无符号整数的数组Uint32Array
an array of 32-bit unsigned integersUint32Array
32位无符号整数的数组Float32Array
an array of 32-bit floating point numbersFloat32Array
32位浮点数的数组Float64Array
an array of 64-bit floating point numbersFloat64Array
64位浮点数的数组
all of them are ArrayBufferView
instances.
它们都是ArrayBufferView
实例。
A Typed Array is essentially a view into an ArrayBuffer
, where every item has the same size, and type.
类型化数组本质上是ArrayBuffer
的视图,其中每个项目的大小和类型都相同。
DataView
is another view into an ArrayBuffer, but in this case the items in the array can have different sizes and types.
DataView
是ArrayBuffer的另一个视图,但是在这种情况下,数组中的项目可以具有不同的大小和类型。
Here’s an example of how to create an array of 8-bit signed integers:
这是一个如何创建一个8位带符号整数数组的示例:
const a = new Int8Array()
You can pre-allocate n bytes:
您可以预分配n个字节:
const bytes = 1024
const a = new Int8Array(bytes)
The main use is to allow to look into an ArrayBuffer, which on its own is opaque (we can’t inspect its content).
主要用途是允许查看ArrayBuffer,它本身是不透明的(我们无法检查其内容)。
Here’s how we do so:
我们的操作方法如下:
//we got this `buffer` ArrayBuffer
const a = new Int8Array(buffer)
Those typed arrays are array-like, so now we can inspect the content of the buffer via the usual array access techniques, and we have access to lots of methods and properties including map()
, reduce()
and so on.
这些类型化的数组类似于数组,因此现在我们可以通过常用的数组访问技术检查缓冲区的内容,并且可以访问许多方法和属性,包括map()
, reduce()
等。
The main use case for Typed Arrays is to use with WebGL, Web Audio or the Canvas API. Some of the WebGL functions are expecting typed arrays, as they are much more performant than regular JavaScript arrays.
类型数组的主要用例是与WebGL , Web Audio或Canvas API一起使用 。 一些WebGL函数期望使用类型化数组,因为它们比常规JavaScript数组具有更高的性能。
One thing to keep in mind is that typed arrays don’t let us control the endianness: it uses the byte order of the platform. In general this works out fine, because the main use case as we said is to use the array locally, using one of the multimedia APIs. Also, most consumer computers use little endian since Intel uses that convention. But, if you transfer the data of a Typed Array on a system that uses big endian, the data might be badly encoded and, as such, invalid.
要记住的一件事是,类型数组不允许我们控制字节序 : 它使用平台的字节顺序 。 总的来说,这很好,因为我们所说的主要用例是使用多媒体API之一在本地使用数组。 另外,由于英特尔使用该约定,因此大多数消费类计算机都使用低位字节序。 但是,如果在使用大字节序的系统上传输类型数组的数据,则数据可能编码错误,因此无效。
In case you need this kind of control over endianness, use DataView instead.
如果您需要这种对字节序的控制,请改用DataView 。
数组类型