TypedArray

TypedArray 物件表示了一個底層 ArrayBuffer 的類陣列(array-like)視圖,它能以限定的型別解讀、修改 ArrayBuffer。但並沒有名為 TypedArray 的內建物件,TypedArray 也不存在可直接呼叫的建構式。真正能夠使用的是幾個原型繼承自 TypedArray 的內建物件,它們可以建立限定成員型別的物件實體來操作 ArrayBuffer。這些 TypedArray 型別的物件僅為視圖,並不會存放資料,所有的資料皆實際儲存於 ArrayBuffer 物件當中。以下將說明每種限定成員型別之 TypedArray 的共同屬性與方法。

嘗試一下

語法

new TypedArray(length);
new TypedArray(typedArray);
new TypedArray(object);
new TypedArray(buffer [, byteOffset [, length]]);

where TypedArray() is one of:

Int8Array();
Uint8Array();
Uint8ClampedArray();
Int16Array();
Uint16Array();
Int32Array();
Uint32Array();
Float32Array();
Float64Array();

參數

length

When called with a length argument, a typed array containing length zeroes is created.

typedArray

When called with a typedArray argument, which can be an object of any of the typed array types (such as Int32Array), the typedArray gets copied into a new typed array. Each value in typedArray is converted to the corresponding type of the constructor before being copied into the new array.

object

When called with an object argument, a new typed array is created as if by the TypedArray.from() method.

buffer, byteOffset, length

When called with a buffer, and optionally a byteOffset and a length argument, a new typed array view is created that views the specified ArrayBuffer. The byteOffset and length parameters specify the memory range that will be exposed by the typed array view. If both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is viewed.

說明

ECMAScript 2015 defines a TypedArray constructor that serves as the [[Prototype]] of all TypedArray constructors. This constructor is not directly exposed: there is no global %TypedArray% or TypedArray property. It is only directly accessible through Object.getPrototypeOf(Int8Array) and similar. All TypedArrays constructors inherit common properties from the %TypedArray% constructor function. Additionally, all typed array prototypes (TypedArray.prototype) have %TypedArray%.prototype as their [[Prototype]].

The %TypedArray% constructor on its own is not particularly useful. Calling it or using it in a new expression will throw a TypeError, except when used during object creation in JS engines that support subclassing. There are at present no such engines, so %TypedArray% is only useful to polyfill functions or properties onto all TypedArray constructors.

When creating an instance of a TypedArray (e.g. Int8Array), an array buffer is created internally in memory or, if an ArrayBuffer object is given as constructor argument, then this is used instead. The buffer address is saved as an internal property of the instance and all the methods of %TypedArray%.prototype, i.e. set value and get value etc., operate on that array buffer address.

Property access

You can reference elements in the array using standard array index syntax (that is, using bracket notation). However, getting or setting indexed properties on typed arrays will not search in the prototype chain for this property, even when the indices are out of bound. Indexed properties will consult the ArrayBuffer and will never look at object properties. You can still use named properties, just like with all objects.

// Setting and getting using standard array syntax
var int16 = new Int16Array(2);
int16[0] = 42;
console.log(int16[0]); // 42

// Indexed properties on prototypes are not consulted (Fx 25)
Int8Array.prototype[20] = 'foo';
(new Int8Array(32))[20]; // 0
// even when out of bound
Int8Array.prototype[20] = 'foo';
(new Int8Array(8))[20]; // undefined
// or with negative integers
Int8Array.prototype[-1] = 'foo';
(new Int8Array(8))[-1]; // undefined

// Named properties are allowed, though (Fx 30)
Int8Array.prototype.foo = 'bar';
(new Int8Array(32)).foo; // "bar"

TypedArray 物件

Type Value Range Size in bytes Description Web IDL type Equivalent C type
Int8Array (en-US) -128 to 127 1 8-bit two's complement signed integer byte int8_t
Uint8Array (en-US) 0 to 255 1 8-bit unsigned integer octet uint8_t
Uint8ClampedArray (en-US) 0 to 255 1 8-bit unsigned integer (clamped) octet uint8_t
Int16Array (en-US) -32768 to 32767 2 16-bit two's complement signed integer short int16_t
Uint16Array (en-US) 0 to 65535 2 16-bit unsigned integer unsigned short uint16_t
Int32Array (en-US) -2147483648 to 2147483647 4 32-bit two's complement signed integer long int32_t
Uint32Array (en-US) 0 to 4294967295 4 32-bit unsigned integer unsigned long uint32_t
Float32Array (en-US) 1.2x10^-38 to 3.4x10^38 4 32-bit IEEE floating point number ( 7 significant digits e.g. 1.1234567) unrestricted float float
Float64Array (en-US) 5.0x10^-324 to 1.8x10^308 8 64-bit IEEE floating point number (16 significant digits e.g. 1.123...15) unrestricted double double

屬性

TypedArray.BYTES_PER_ELEMENT (en-US)

Returns a number value of the element size for the different typed array objects.

TypedArray.length

Length property whose value is 0.

TypedArray.name (en-US)

Returns the string value of the constructor name. E.g "Int8Array".

get TypedArray[@@species] (en-US)

The constructor function that is used to create derived objects.

TypedArray.prototype (en-US)

Prototype for the TypedArray objects.

方法

TypedArray.from() (en-US)

Creates a new typed array from an array-like or iterable object. See also Array.from().

TypedArray.of() (en-US)

Creates a new typed array with a variable number of arguments. See also Array.of().

TypedArray 原型

All TypedArrays inherit from TypedArray.prototype (en-US).

屬性

These properties are all getters defined on the TypedArray prototype object and are thus read-only and shared by all TypedArray subclass instances.

TypedArray.prototype[@@toStringTag]

The initial value of a typed array's @@toStringTag (en-US) property is the same string as its name (en-US). This property is used in Object.prototype.toString() (en-US). However, because TypedArray also has its own toString() (en-US) method, this property is not used unless you call Object.prototype.toString.call() with a typed array as thisArg.

TypedArray.prototype.buffer (en-US)

Returns the ArrayBuffer referenced by the typed array.

TypedArray.prototype.byteLength (en-US)

Returns the length (in bytes) of the typed array.

TypedArray.prototype.byteOffset (en-US)

Returns the offset (in bytes) of the typed array from the start of its ArrayBuffer.

TypedArray.prototype.length (en-US)

Returns the number of elements held in the typed array.

All TypedArray subclasses also have the following instance properties:

TypedArray.prototype.BYTES_PER_ELEMENT (en-US)

Returns a number value of the element size for the different TypedArray objects.

方法

These methods are defined on the TypedArray prototype object and are thus shared by all TypedArray subclass instances.

TypedArray.prototype.at() (en-US)

Takes an integer value and returns the item at that index. This method allows for negative integers, which count back from the last item.

TypedArray.prototype.copyWithin() (en-US)

Copies a sequence of array elements within the array. See also Array.prototype.copyWithin().

TypedArray.prototype.entries() (en-US)

Returns a new array iterator object that contains the key/value pairs for each index in the array. See also Array.prototype.entries().

TypedArray.prototype.every() (en-US)

Tests whether all elements in the array pass the test provided by a function. See also Array.prototype.every().

TypedArray.prototype.fill() (en-US)

Fills all the elements of an array from a start index to an end index with a static value. See also Array.prototype.fill().

TypedArray.prototype.filter() (en-US)

Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter().

TypedArray.prototype.find() (en-US)

Returns the first element in the array that satisfies a provided testing function, or undefined if no appropriate element is found. See also Array.prototype.find().

TypedArray.prototype.findIndex() (en-US)

Returns the first index value of in the array that has an element that satisfies a provided testing function, or -1 if no appropriate element was found. See also Array.prototype.findIndex().

TypedArray.prototype.findLast() (en-US)

Returns the value of the last element in the array that satisfies a provided testing function, or undefined if no appropriate element is found. See also Array.prototype.findLast() (en-US).

TypedArray.prototype.findLastIndex() (en-US)

Returns the index of the last element in the array that satisfies a provided testing function, or -1 if no appropriate element was found. See also Array.prototype.findLastIndex() (en-US).

TypedArray.prototype.forEach() (en-US)

Calls a function for each element in the array. See also Array.prototype.forEach().

TypedArray.prototype.includes() (en-US)

Determines whether a typed array includes a certain element, returning true or false as appropriate. See also Array.prototype.includes().

TypedArray.prototype.indexOf() (en-US)

Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. See also Array.prototype.indexOf().

TypedArray.prototype.join() (en-US)

Joins all elements of an array into a string. See also Array.prototype.join().

TypedArray.prototype.keys() (en-US)

Returns a new array iterator that contains the keys for each index in the array. See also Array.prototype.keys().

TypedArray.prototype.lastIndexOf() (en-US)

Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found. See also Array.prototype.lastIndexOf().

TypedArray.prototype.map() (en-US)

Creates a new array with the results of calling a provided function on every element in this array. See also Array.prototype.map().

TypedArray.prototype.reduce() (en-US)

Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value. See also Array.prototype.reduce().

TypedArray.prototype.reduceRight() (en-US)

Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value. See also Array.prototype.reduceRight() (en-US).

TypedArray.prototype.reverse() (en-US)

Reverses the order of the elements of an array — the first becomes the last, and the last becomes the first. See also Array.prototype.reverse().

TypedArray.prototype.set() (en-US)

Stores multiple values in the typed array, reading input values from a specified array.

TypedArray.prototype.slice() (en-US)

Extracts a section of an array and returns a new array. See also Array.prototype.slice().

TypedArray.prototype.some() (en-US)

Returns true if at least one element in this array satisfies the provided testing function. See also Array.prototype.some().

TypedArray.prototype.sort() (en-US)

Sorts the elements of an array in place and returns the array. See also Array.prototype.sort().

TypedArray.prototype.subarray() (en-US)

Returns a new TypedArray from the given start and end element index.

TypedArray.prototype.values() (en-US)

Returns a new array iterator object that contains the values for each index in the array. See also Array.prototype.values().

TypedArray.prototype.toLocaleString() (en-US)

Returns a localized string representing the array and its elements. See also Array.prototype.toLocaleString() (en-US).

TypedArray.prototype.toString() (en-US)

Returns a string representing the array and its elements. See also Array.prototype.toString().

TypedArray.prototype[@@iterator]() (en-US)

Returns a new array iterator object that contains the values for each index in the array.

Methods Polyfill

Many of the methods used in Typed Arrays can be polyfilled using the methods present in regular Javascript Arrays. The following snippet of JavaScript demonstrates how you might polyfill any missing Typed Array methods.

var typedArrayTypes = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array,
          Uint16Array, ​​​Int32Array, Uint32Array, ​​​Float32Array, Float64Array];

for (var k in typedArrayTypes)
    for (var v in Array.prototype)
        if (Array.prototype.hasOwnProperty(v) &&
          !typedArrayTypes[k].prototype.hasOwnProperty(v))
            typedArrayTypes[k].prototype[v] = Array.prototype[v];

規範

Specification
ECMAScript Language Specification
# sec-typedarray-objects

瀏覽器相容性

BCD tables only load in the browser

相容性備註

Starting with ECMAScript 2015, TypedArray constructors require to be constructed with a new operator. Calling a TypedArray constructor as a function without new, will throw a TypeError (en-US) from now on.

var dv = Int8Array([1, 2, 3]);
// TypeError: calling a builtin Int8Array constructor
// without new is forbidden
var dv = new Int8Array([1, 2, 3]);

參見