Open In App

JavaScript DataView()

Last Updated : 30 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Example: This example shows the use of the JavaScript DataView() function.

javascript
// Creating an ArrayBuffer with a size in bytes
let buffer = new ArrayBuffer(16);

// Creating views
let view1 = new DataView(buffer);

// Creating view from byte 0 for the next 4 bytes
let view2 = new DataView(buffer, 0, 4);

// Creating view from byte 12 for the next 2 bytes
let 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
console.log(view2.getInt8(0));
console.log(view3.getInt8(0));

Output:

1
2


Next Article
Article Tags :

Similar Reads