CKTIS / JavaScript
Int16Array: inteiros com sinal de 16 bits
Int16Array guarda números como inteiros com sinal de 16 bits entre -32768 e 32767, com 2 bytes por elemento.
Versão: ECMAScript 2015 onward; example target: Node.js 24.22.2
Sintaxe
new Int16Array(); new Int16Array(length); new Int16Array(source); new Int16Array(buffer[, byteOffset[, length]])new Int16Array(source?, byteOffset?, length?) cria um typed array numérico a partir de comprimento, iterable/array-like, outro typed array numérico ou ArrayBuffer/SharedArrayBuffer. A forma com buffer não copia bytes, byteOffset tem de ser múltiplo de 2 e BYTES_PER_ELEMENT é 2.
A atribuição aplica ToNumber, trunca a fração, reduz módulo 2^16 e interpreta o resultado com sinal. Assim 32768 torna-se -32768, 65535 torna-se -1, e NaN e infinitos tornam-se 0. Atribuir BigInt ou usar typed array BigInt como origem lança TypeError. A ordem dos bytes é nativa; usa DataView para endianness explícito.
O comprimento passa por ToIndex: frações são truncadas, NaN/undefined tornam-se 0 e -0.5 dá 0. Resultado negativo após ToIntegerOrInfinity, infinito, offset desalinhado ou intervalo fora do buffer lança RangeError; buffer separado lança TypeError. O tipo é padrão desde ECMAScript 2015.
Exemplos
const values = new Int16Array([32767, 32768, 65535, -32769, 3.9, NaN, Infinity]);
console.log(Array.from(values).join(","));
console.log(Int16Array.BYTES_PER_ELEMENT, new Int16Array(2.9).length, new Int16Array(-0.5).length);
const buffer = new ArrayBuffer(6);
const view = new Int16Array(buffer, 2, 1);
view[0] = -1234;
console.log(view.byteOffset, view.byteLength, view[0]);
try { view[0] = 1n; } catch (error) { console.log(error instanceof TypeError); }Resultado
32767,-32768,-1,32767,3,0,0 2 2 0 2 2 -1234 true