JavaScript | DataView()
The DataView function in JavaScript provides an interface to read and write more than one number types into an ArrayBuffer.
Syntax:
new DataView(buffer, byteOffset, byteLength)
Parameters: The function accepts three parameters which are described as below:
- buffer: An ArrayBuffer that is already existing to store the new DataView object.
- byteOffset (optional): offset(in bytes) in the buffer is used to start a new view of the buffer. By default, the new view starts from the first byte.
- byteLength (optional): It represents number of elements in the byte array. By default, the buffer’s length is considered as the length of the view.
Return value: It returns a new DataView object which will represent the specified data buffer.
Code#1:
<script> // Creating an ArrayBuffer with a size in bytes var buffer = new ArrayBuffer(16); // Creating views var view1 = new DataView(buffer); //creating view from byte 0 for the next 4 bytes var view2 = new DataView(buffer,0,4); //creating view from byte 12 for the next 2 bytes var view3 = new DataView(buffer,12,2); // Putting 1 in slot 0 view1.setInt8(0, 1); // Putting 2 in slot 12 view1.setInt8(12, 2) //printing the views document.write(view2.getInt8(0)+ '<br>' ); document.write(view3.getInt8(0)+ '<br>' ); </script> |
Output:
1 2