JavaScript typedArray.subarray() with Examples
The Javascript typedArray.subarray() is an inbuilt function in JavaScript that is used to return a part of the typedArray object.
Syntax:
typedarray.subarray(begin, end);
Parameters:
- begin: It specifies the index of the starting element from which the part of the given array is to be started. It is optional and inclusive.
- end: It specifies the index of the ending element up to which the part of the given array is to be included. It is optional and exclusive.
Return value:
It returns a new array that is formed from the given typedArray object.
Example 1: This example shows the basic use of the typedArray.subarray() function. Here it returns the value of the subarray with the given parameters.
javascript
// Creating a new typedArray Uint8Array() object const A = new Uint8Array([5, 10, 15, 20, 25, 30, 35]); // Calling subarray() functions B = A.subarray(1, 3) C = A.subarray(1) D = A.subarray(3) E = A.subarray(0, 6) F = A.subarray(0) // Printing some new typedArray which are // the part of the given input typedArray console.log(B); console.log(C); console.log(D); console.log(E); console.log(F); |
Uint8Array(2) [ 10, 15 ] Uint8Array(6) [ 10, 15, 20, 25, 30, 35 ] Uint8Array(4) [ 20, 25, 30, 35 ] Uint8Array(6) [ 5, 10, 15, 20, 25, 30 ] Uint8Array(7) [ 5, 10, 15, 20, 25, 30, 35 ]
Example 2: When the index is negative then elements get accessed from the end of the typedArray object. Below is the required code which illustrates this negative indexing concept.
javascript
// Creating a new typedArray Uint8Array() object const A = new Uint8Array([5, 10, 15, 20, 25, 30, 35]); // Calling subarray() functions B = A.subarray(-1) C = A.subarray(-2) D = A.subarray(-3) E = A.subarray(3) F = A.subarray(0) // Printing some new typedArray which are // the part of the given input typedArray console.log(B); console.log(C); console.log(D); console.log(E); console.log(F); |
Uint8Array(1) [ 35 ] Uint8Array(2) [ 30, 35 ] Uint8Array(3) [ 25, 30, 35 ] Uint8Array(4) [ 20, 25, 30, 35 ] Uint8Array(7) [ 5, 10, 15, 20, 25, 30, 35 ]
The output includes “Uint8Array” because A.subarray()
returns a new Uint8Array
object. The subarray()
method in JavaScript creates a shallow copy of a portion of an array into a new array object. In this case, it’s a portion of the original Uint8Array
object A
.
Contact Us