Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

TypedArray

BaselineWidely available *

ATypedArray object describes an array-like view of anunderlyingbinary data buffer.There is no global property namedTypedArray, nor is there adirectly visibleTypedArray constructor. Instead, there are a number ofdifferent global properties, whose values are typed array constructors for specificelement types, listed below. On the following pages you will find common properties andmethods that can be used with any typed array containing elements of any type.

Description

TheTypedArray constructor (often referred to as%TypedArray% to indicate its "intrinsicness", since it does not correspond to any global exposed to a JavaScript program) serves as the common superclass of allTypedArray subclasses. Think about%TypedArray% as an "abstract class" providing a common interface of utility methods for all typed array subclasses. This constructor is not directly exposed: there is no globalTypedArray property. It is only accessible throughObject.getPrototypeOf(Int8Array) and similar.

When creating an instance of aTypedArray subclass (e.g.,Int8Array), an array buffer is created internally in memory or, if anArrayBuffer object is given as constructor argument, thatArrayBuffer is used instead. The buffer address is saved as an internal property of the instance and all the methods of%TypedArray%.prototype will set and get values based on that array buffer address.

TypedArray objects

TypeValue RangeSize in bytesWeb IDL type
Int8Array-128 to 1271byte
Uint8Array0 to 2551octet
Uint8ClampedArray0 to 2551octet
Int16Array-32768 to 327672short
Uint16Array0 to 655352unsigned short
Int32Array-2147483648 to 21474836474long
Uint32Array0 to 42949672954unsigned long
Float16Array-65504 to655042N/A
Float32Array-3.4e38 to3.4e384unrestricted float
Float64Array-1.8e308 to1.8e3088unrestricted double
BigInt64Array-263 to 263 - 18bigint
BigUint64Array0 to 264 - 18bigint

Value encoding and normalization

All typed arrays operate onArrayBuffers, where you can observe the exact byte representation of each element, so how the numbers are encoded in binary format is significant.

  • Unsigned integer arrays (Uint8Array,Uint16Array,Uint32Array, andBigUint64Array) store the number directly in binary.
  • Signed integer arrays (Int8Array,Int16Array,Int32Array, andBigInt64Array) store the number usingtwo's complement.
  • Floating-point arrays (Float16Array,Float32Array, andFloat64Array) store the number usingIEEE 754 floating-point format. TheNumber reference has more information about the exact format. JavaScript numbers use double precision floating point format by default, which is the same asFloat64Array.Float32Array uses 23 (instead of 52) bits for the mantissa and 8 (instead of 11) bits for the exponent.Float16Array uses 10 bits for the mantissa and 5 bits for the exponent. Note that the spec requires allNaN values to use the same bit encoding, but the exact bit pattern is implementation-dependent.
  • Uint8ClampedArray is a special case. It stores the number in binary likeUint8Array does, but when you store a number outside the range, itclamps the number to the range 0 to 255 by mathematical value, instead of truncating the most significant bits.

All typed arrays exceptInt8Array,Uint8Array, andUint8ClampedArray store each element using multiple bytes. These bytes can either be ordered from most significant to least significant (big-endian) or from least significant to most significant (little-endian). SeeEndianness for more explanation. Typed arrays always use the platform's native byte order. If you want to specify the endianness when writing and reading from buffers, you should use aDataView instead.

When writing to these typed arrays, values that are outside the representable range are normalized.

  • All integer arrays (exceptUint8ClampedArray) usefixed-width number conversion, which first truncates the decimal part of the number and then takes the lowest bits.
  • Uint8ClampedArray first clamps the number to the range 0 to 255 (values greater than 255 become 255 and values less than 0 become 0). It thenrounds (instead of flooring) the result to the nearest integer, with half-to-even; meaning if the number is exactly between two integers, it rounds to the nearest even integer. For example,0.5 becomes0,1.5 becomes2, and2.5 becomes2.
  • Float16Array andFloat32Array perform a "round to even" to convert 64-bit floating point numbers to 32-bit and 16-bit. This is the same algorithm as provided byMath.fround() andMath.f16round().

Behavior when viewing a resizable buffer

When aTypedArray is created as a view of aresizable buffer, resizing the underlying buffer will have different effects on the size of theTypedArray depending on whether theTypedArray is constructed as length-tracking.

If a typed array is created without a specific size by omitting the third parameter or passingundefined, the typed array will becomelength-tracking, and will automatically resize to fit the underlyingbuffer as the latter is resized:

js
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });const float32 = new Float32Array(buffer);console.log(float32.byteLength); // 8console.log(float32.length); // 2buffer.resize(12);console.log(float32.byteLength); // 12console.log(float32.length); // 3

If a typed array is created with a specific size using the thirdlength parameter, it won't resize to contain thebuffer as the latter is grown:

js
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });const float32 = new Float32Array(buffer, 0, 2);console.log(float32.byteLength); // 8console.log(float32.length); // 2console.log(float32[0]); // 0, the initial valuebuffer.resize(12);console.log(float32.byteLength); // 8console.log(float32.length); // 2console.log(float32[0]); // 0, the initial value

When abuffer is shrunk, the viewing typed array may become out of bounds, in which case the typed array's observed size will decrease to 0. This is the only case where a non-length-tracking typed array's length may change.

js
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });const float32 = new Float32Array(buffer, 0, 2);buffer.resize(7);console.log(float32.byteLength); // 0console.log(float32.length); // 0console.log(float32[0]); // undefined

If you then grow thebuffer again to bring the typed array back in bounds, the typed array's size will be restored to its original value.

js
buffer.resize(8);console.log(float32.byteLength); // 8console.log(float32.length); // 2console.log(float32[0]); // 0 - back in bounds again!

The same can happen for length-tracking typed arrays as well, if the buffer is shrunk beyond thebyteOffset.

js
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });const float32 = new Float32Array(buffer, 4);// float32 is length-tracking, but it only extends from the 4th byte// to the end of the buffer, so if the buffer is resized to be shorter// than 4 bytes, the typed array will become out of boundsbuffer.resize(3);console.log(float32.byteLength); // 0

Constructor

This object cannot be instantiated directly — attempting to construct it withnew throws aTypeError.

js
new (Object.getPrototypeOf(Int8Array))();// TypeError: Abstract class TypedArray not directly constructable

Instead, you create an instance of a typed array of a particular type, such as anInt8Array or aBigInt64Array. These objects all have a common syntax for their constructors:

js
new TypedArray()new TypedArray(length)new TypedArray(typedArray)new TypedArray(object)new TypedArray(buffer)new TypedArray(buffer, byteOffset)new TypedArray(buffer, byteOffset, length)

WhereTypedArray is a constructor for one of the concrete types.

Note:AllTypedArray subclasses' constructors can only be constructed withnew. Attempting to call one withoutnew throws aTypeError.

Parameters

typedArray

When called with an instance of aTypedArray subclass, thetypedArray gets copied into a new typed array. For a non-bigintTypedArray constructor, thetypedArray parameter can only be of one of the non-bigint types (such asInt32Array). Similarly, for abigintTypedArray constructor (BigInt64Array orBigUint64Array), thetypedArray parameter can only be of one of thebigint types. Each value intypedArray is converted to the corresponding type of the constructor before being copied into the new array. The length of the new typed array will be same as the length of thetypedArray argument.

object

When called with an object that's not aTypedArray instance, a new typed array is created in the same way as theTypedArray.from() method.

lengthOptional

When called with a non-object, the parameter will be treated as a number specifying the length of the typed array. An internal array buffer is created in memory, of sizelength multiplied byBYTES_PER_ELEMENT bytes, filled with zeros. Omitting all parameters is equivalent to using0 aslength.

buffer,byteOffsetOptional,lengthOptional

When called with anArrayBuffer orSharedArrayBuffer instance, and optionally abyteOffset and alength argument, a new typed array view is created that views the specified buffer. ThebyteOffset (in bytes) andlength (in number of elements, each occupyingBYTES_PER_ELEMENT bytes) parameters specify the memory range that will be exposed by the typed array view. If both are omitted, all ofbuffer is viewed; if onlylength is omitted, the remainder ofbuffer starting frombyteOffset is viewed. Iflength is omitted, the typed array becomeslength-tracking.

Exceptions

AllTypeArray subclass constructors operate in the same way. They would all throw the following exceptions:

TypeError

Thrown in one of the following cases:

  • AtypedArray is passed but it is abigint type while the current constructor is not, or vice versa.
  • AtypedArray is passed but the buffer it's viewing is detached, or a detachedbuffer is directly passed.
RangeError

Thrown in one of the following cases:

  • The new typed array's length is too large.
  • The length ofbuffer (if thelength parameter is not specified) orbyteOffset is not an integral multiple of the new typed array's element size.
  • byteOffset is not a valid array index (an integer between 0 and 253 - 1).
  • When creating a view from a buffer, the bounds are outside the buffer. In other words,byteOffset + length * TypedArray.BYTES_PER_ELEMENT > buffer.byteLength.

Static properties

These properties are defined on theTypedArray constructor object and are thus shared by allTypedArray subclass constructors.

TypedArray[Symbol.species]

The constructor function used to create derived objects.

AllTypedArray subclasses also have the following static properties:

TypedArray.BYTES_PER_ELEMENT

Returns a number value of the element size for the differentTypedArray objects.

Static methods

These methods are defined on theTypedArray constructor object and are thus shared by allTypedArray subclass constructors.

TypedArray.from()

Creates a newTypedArray from an array-like or iterable object. See alsoArray.from().

TypedArray.of()

Creates a newTypedArray with a variable number of arguments. See alsoArray.of().

Instance properties

These properties are defined onTypedArray.prototype and shared by allTypedArray subclass instances.

TypedArray.prototype.buffer

Returns theArrayBuffer referenced by the typed array.

TypedArray.prototype.byteLength

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

TypedArray.prototype.byteOffset

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

TypedArray.prototype.constructor

The constructor function that created the instance object.TypedArray.prototype.constructor is the hiddenTypedArray constructor function, but each typed array subclass also defines its ownconstructor property.

TypedArray.prototype.length

Returns the number of elements held in the typed array.

TypedArray.prototype[Symbol.toStringTag]

The initial value of theTypedArray.prototype[Symbol.toStringTag] property is a getter that returns the same string as the typed array constructor's name. It returnsundefined if thethis value is not one of the typed array subclasses. This property is used inObject.prototype.toString(). However, becauseTypedArray also has its owntoString() method, this property is not used unless you callObject.prototype.toString.call() with a typed array asthisArg.

AllTypedArray subclasses also have the following instance properties:

TypedArray.prototype.BYTES_PER_ELEMENT

Returns a number value of the element size for the differentTypedArray objects.

Instance methods

These methods are defined on theTypedArray prototype object and are thus shared by allTypedArray subclass instances.

TypedArray.prototype.at()

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()

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

TypedArray.prototype.entries()

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

TypedArray.prototype.every()

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

TypedArray.prototype.fill()

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

TypedArray.prototype.filter()

Creates a new array with all of the elements of this array for which the provided filtering function returnstrue. See alsoArray.prototype.filter().

TypedArray.prototype.find()

Returns the firstelement in the array that satisfies a provided testing function, orundefined if no appropriate element is found. See alsoArray.prototype.find().

TypedArray.prototype.findIndex()

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

TypedArray.prototype.findLast()

Returns the value of the last element in the array that satisfies a provided testing function, orundefined if no appropriate element is found. See alsoArray.prototype.findLast().

TypedArray.prototype.findLastIndex()

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 alsoArray.prototype.findLastIndex().

TypedArray.prototype.forEach()

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

TypedArray.prototype.includes()

Determines whether a typed array includes a certain element, returningtrue orfalse as appropriate. See alsoArray.prototype.includes().

TypedArray.prototype.indexOf()

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

TypedArray.prototype.join()

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

TypedArray.prototype.keys()

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

TypedArray.prototype.lastIndexOf()

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

TypedArray.prototype.map()

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

TypedArray.prototype.reduce()

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 alsoArray.prototype.reduce().

TypedArray.prototype.reduceRight()

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 alsoArray.prototype.reduceRight().

TypedArray.prototype.reverse()

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

TypedArray.prototype.set()

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

TypedArray.prototype.slice()

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

TypedArray.prototype.some()

Returnstrue if at least one element in this array satisfies the provided testing function. See alsoArray.prototype.some().

TypedArray.prototype.sort()

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

TypedArray.prototype.subarray()

Returns a newTypedArray from the given start and end element index.

TypedArray.prototype.toLocaleString()

Returns a localized string representing the array and its elements. See alsoArray.prototype.toLocaleString().

TypedArray.prototype.toReversed()

Returns a new array with the elements in reversed order, without modifying the original array.

TypedArray.prototype.toSorted()

Returns a new array with the elements sorted in ascending order, without modifying the original array.

TypedArray.prototype.toString()

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

TypedArray.prototype.values()

Returns a newarray iterator object that contains the values for each index in the array. See alsoArray.prototype.values().

TypedArray.prototype.with()

Returns a new array with the element at the given index replaced with the given value, without modifying the original array.

TypedArray.prototype[Symbol.iterator]()

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

Examples

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 arrayswill not search in the prototype chain for this property, even when the indices are outof bound. Indexed properties will consult theArrayBuffer and will neverlook at object properties. You can still use named properties, just like with allobjects.

js
// Setting and getting using standard array syntaxconst 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 boundInt8Array.prototype[20] = "foo";new Int8Array(8)[20]; // undefined// or with negative integersInt8Array.prototype[-1] = "foo";new Int8Array(8)[-1]; // undefined// Named properties are allowed, though (Fx 30)Int8Array.prototype.foo = "bar";new Int8Array(32).foo; // "bar"

Cannot be frozen

TypedArrays that aren't empty cannot be frozen, as theirunderlyingArrayBuffer could be mutated through anotherTypedArray view of the buffer. This would mean that the objectwould never genuinely be frozen.

js
const i8 = Int8Array.of(1, 2, 3);Object.freeze(i8);// TypeError: Cannot freeze array buffer views with elements

ByteOffset must be aligned

When constructing aTypedArray as a view onto anArrayBuffer, thebyteOffset argument must be aligned to itselement size; in other words, the offset must be a multiple ofBYTES_PER_ELEMENT.

js
const i32 = new Int32Array(new ArrayBuffer(4), 1);// RangeError: start offset of Int32Array should be a multiple of 4
js
const i32 = new Int32Array(new ArrayBuffer(4), 0);

ByteLength must be aligned

Like thebyteOffset parameter, thebyteLength property of anArrayBuffer passed to aTypedArray's constructormust be a multiple of the constructor'sBYTES_PER_ELEMENT.

js
const i32 = new Int32Array(new ArrayBuffer(3));// RangeError: byte length of Int32Array should be a multiple of 4
js
const i32 = new Int32Array(new ArrayBuffer(4));

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-typedarray-objects

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp