|Written by Ian Elliot|
|Thursday, 28 February 2019|
Page 3 of 3
One of the very standard operations that you have to perform with binary data is moving it from one place to another. The direct and not very efficient way of doing this is to simply write a suitable for loop that transfers the data one element at a time.
A better method is to use the typed array's set method which will transfer the contents of one array or part of an array to another.
copys all of the contents of array2 into array1 and
copys all of array2 into array1 starting at array1[offset]
If for any reason the copy operation results in an attempt to access beyond the end of array1 then an exception is thrown.
You can even use set to move data within a single ArrayBuffer. For example, if we set the first 50 bytes of an array to 255 and then define a view of these first 50 bytes we can use this to move all 50 to the top of the array:
In fact we can make this example even simpler by using the subarray method which constructs a new view on the same buffer that is:
returns a view, array2, into the same ArrayBuffer as array1 uses. The new view starts with array1[start] and has length elements.
So to get we could write the previous example as:
or if you prefer one-liners:
This might be all you need to know about typed arrays but there is more. Specifically there is the difficult question of byte order that we need to solve and how to work with binary data that isn't all of one type, i.e. a binary structure or record. You can find out how all of this works in part II of our look at typed arrays.
|Last Updated ( Thursday, 28 February 2019 )|