JavaScript DataView setInt8() 方法



JavaScript DataView 的 setInt8() 方法用於將一個 8 位有符號整數的值儲存到 DataView 中指定 byteOffset 位置的位元組 (1 位元組 = 8 位) 中。

如果 byteOffset 引數值超出此 DataView 的範圍,此方法將丟擲 'RangeError'

語法

以下是 JavaScript DataView setInt8() 方法的語法:

setInt8(byteOffset, value)

引數

此方法接受兩個名為“byteOffset”和“value”的引數,如下所述:

  • byteOffset - DataView 中將儲存位元組的位置。
  • value - 需要儲存的有符號 8 位整數。

返回值

此方法返回 'undefined'

示例 1

以下程式演示了 JavaScript DataView setInt8() 方法的用法。

<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>

輸出

上述程式返回 'undefined':

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

示例 2

在下面的示例中,我們使用 setInt8() 方法將 8 位有符號整數 43234 儲存到此 DataView 中指定 byteOffset 為 0 的位元組中。

<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>

輸出

執行上述程式後,它將把給定的值 20 儲存到此 DataView 的位元組中:

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

示例 3

如果 byteOffset 引數的值超出此 DataView 的範圍,它將丟擲 'RangeError' 異常。

<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>

輸出

執行上述程式後,它將丟擲 'RangeError' 異常。

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