Open In App

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:

Return value: It returns a new DataView object which will represent the specified data buffer.

JavaScript code to show the working of DataView() function:

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
Article Tags :