JavaScript DataView getInt32() 方法



JavaScript DataView 的getInt32() 方法用於從指定的位元組偏移量檢索 4 位元組資料值,並將其解碼為32 位有符號整數。可以從資料檢視範圍內的任何偏移量獲取多個位元組值。

如果byteOffset 引數的值超出此資料檢視的範圍,則會丟擲'RangeError' 異常。

語法

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

getInt32(byteOffset, littleEndian)

引數

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

  • byteOffset - 從 DataView 中讀取資料的位置。
  • littleEndian - 指示資料是以小端還是大端格式儲存。

返回值

此方法返回一個整數,範圍從-21474836482147483647(含)。

示例 1

以下示例演示了 JavaScript DataView getInt32() 方法的使用。

<html>
<body>
<script>
   const buffer = new ArrayBuffer(32);
   const data_view = new DataView(buffer);
   const value = 2147483647;
   const byteOffset = 0;
   document.write("Value: ", value);
   document.write("<br>The byte offset: ", byteOffset);
   //storing value
   data_view.setInt32(byteOffset, value);
   document.write("<br>The store value: ", data_view.getInt32(byteOffset));
   </script>
</body>
</html>

輸出

以上程式輸出儲存的值為:

Value: 2147483647
The byte offset: 0
The store value: 2147483647

示例 2

如果未將byteOffset 引數值傳遞給此方法,它將自動返回此資料檢視在 byteOffset 0 處儲存的值。

<html>
<body>
<script>
   const buffer = new ArrayBuffer(32);
   const data_view = new DataView(buffer);
   const value = 2443;
   const byteOffset = 0;
   document.write("Value: ", value);
   document.write("<br>The byte offset: ", byteOffset);
   //storing value
   data_view.setInt32(byteOffset, value);
   document.write("<br>The data_view.getInt32() method returns: ", data_view.getInt32());
</script>
</body>
</html>

輸出

執行以上程式後,它將返回儲存的值“2443”。

Value: 2443
The byte offset: 0
The data_view.getInt32() method returns: 2443

示例 3

如果byteOffset 引數的值超出資料檢視的範圍,則會丟擲'RangeError' 異常。

<html>
<body>
<script>
   const buffer = new ArrayBuffer(32);
   const data_view = new DataView(buffer);
   const value = 2443;
   const byteOffset = 0;
   document.write("Value: ", value);
   document.write("<br>The byte offset: ", byteOffset);
   //storing value
   data_view.setInt32(byteOffset, value);
   try {
      document.write(data_view.getInt32(-1));
   } catch (error) {
      document.write("<br>", error);
   }
</script>
</body>
</html>

輸出

執行以上程式後,將丟擲“RangeError”異常,如下所示:

Value: 2443
The byte offset: 0
RangeError: Offset is outside the bounds of the DataView
廣告