I have the following snippet:
new Uint16Array( arraybuffer, 0, 18108 );
I know that arraybuffer
is an instance of ArrayBuffer, and that arraybuffer.byteLength
is 31984. The content of the arraybuffer is a black box to me. Because the buffer's byteLength is > 18108, I expect this to just work. Instead, I get the following errors:
Chrome:
RangeError: Invalid typed array length
Firefox:
TypeError: invalid arguments
What might cause this to fail, or how can I inspect an ArrayBuffer I can't open?
To fix the ‘RangeError: invalid array length’ when we’re developing JavaScript apps, we should make sure the array length value that we call the Array and ArrayBuffer constructors are called with a valid value. Also, we should make sure we set the length property of an array to a non-negative integer.
Cause of the error: The length of an Array or an ArrayBuffer can only be represented by an unsigned 32-bit integer, which only stores values ranging from 0 to 2 32 -1. While creating an Array or an ArrayBuffer, if the array length is either negative or greater than or equal to 2 32 then this error occurs.
The JavaScript exception "Invalid array length" occurs when creating an Array or an ArrayBuffer which has a length which is either negative or larger or equal to 2 32, or when setting the Array.length property to a value which is either negative or larger or equal to 2 32.
Well, I misunderstood the TypedArray / Uint16Array constructor. The second argument is a byteOffset, but the third argument is not byte length: It is length in elements. When called with a length argument, an internal array buffer is created in memory of size length multiplied by BYTES_PER_ELEMENT bytes containing 0 value.
Well, I misunderstood the TypedArray / Uint16Array constructor. The second argument is a byteOffset
, but the third argument is not byte length: It is length in elements.
From TypedArray docs:
length
When called with a length argument, an internal array buffer is created in memory of size length multiplied by BYTES_PER_ELEMENT bytes containing 0 value.
Since Uint16Array.BYTES_PER_ELEMENT
is 2, the arraybuffer would need to be at least 2 * 18108
bytes long, which it is not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With