Search code examples
javascriptarraysinstancearraybufferuint8array

How do two unequal `Uint8Array`s influence each other when constructed from an `ArrayBuffer`?


I have an ArrayBuffer, and I want to get two separate Uint8Array copies from it. I attempt this by using the Uint8Array constructor on the ArrayBuffer twice. The constructed array instances do not equal. Yet, when you alter one, it alters the other in the same way. How is this possible, and why would this be the case?

Unequal arrays magically influencing each other

On the other hand, if you construct new Uint8Arrays from the constructed Uint8Array, they will be functionally separated as one would expect.

Unequal arrays working properly


Solution

  • The entries inside of a TypedArray are actually stored in the underlying buffer, if you get/set the array, it reads/writes to/from the buffer. If you create a TypedArray from another TypedArray, the underlying buffer will be copied, and therefore the arrays will not be linked.

     array.buffer === array1.buffer // true
     array1.buffer === array2.buffer // false