• JavaScript Video Tutorials

JavaScript DataView setInt8() Method



The JavaScript DataView setInt8() method is used to store an 8-bit signed integer value in the byte (1 byte = 8-bit) at the start of the specified byteOffset of this DataView.

This method throws a 'RangeError' if the byteOffset parameter value is outside the bounds of this DataView.

Syntax

Following is the syntax of the JavaScript DataView setInt8() method −

setInt8(byteOffset, value)

Parameters

This method accepts two parameters named 'byteOffset' and 'value', which are described below −

  • byteOffset − The position in the DataView where the byte will be stored.
  • value − A signed 8-bit integer that needs to be stored.

Return value

This method returns 'undefined'.

Example 1

The following program demonstrates the usage of the JavaScript DataView setInt8() method.

<html>
<body>
<script>
   const buffer = new ArrayBuffer(8);
   const data_view = new DataView(buffer);
   const byteOffset = 1;
   const value = 45;
   document.write("The byteOffset: ", byteOffset);
   document.write("<br>The data value: ", value);
   //using the setInt8() method
   document.write("<br>The setInt8() method returns: ", data_view.setInt8(byteOffset, value));
</script>
</body>
</html>

Output

The above program returns 'undefined' −

The byteOffset: 1
The data value: 45
The setInt8() method returns: undefined

Example 2

In the following example, we use the setInt8() method to store the 8-bit signed integer 43234 in the byte at the specified byteOffset 0 in this DataView.

<html>
<body>
<script>
   const buffer = new ArrayBuffer(8);
   const data_view = new DataView(buffer);
   const byteOffset = 1;
   const value = 20;
   document.write("The byteOffset: ", byteOffset);
   document.write("<br>The data value: ", value);
   //using the setInt8() method
   document.write("<br>The setInt8() method returns: ", data_view.setInt8(byteOffset, value));
   document.write("<br>The stored value: ", data_view.getInt8(byteOffset));
</script>
</body>
</html>

Output

Once the above program is executed, it will store the given value 20 in bytes of this DataView −

The byteOffset: 1
The data value: 20
The setInt8() method returns: undefined
The stored value: 20

Example 3

If the value of the byteOffset parameter is outside the bounds of this DataView, it will throw a 'RangeError' exception.

<html>
<body>
<script>
   const buffer = new ArrayBuffer(8);
   const data_view = new DataView(buffer);
   const byteOffset = -1;
   const value = 10;
   document.write("The byteOffset: ", byteOffset);
   document.write("<br>The data value: ", value);
   try {
      //using the setInt8() method
      data_view.setInt8(byteOffset, value);
   } catch (error) {
      document.write("<br>", error);
   }
</script>
</body>
</html>

Output

After executing the above program, it will throw a 'RangeError' exception.

The byteOffset: -1
The data value: 10
RangeError: Offset is outside the bounds of the DataView
Advertisements