JavaScript DataView getInt16() 方法



JavaScript DataView 的getInt16()方法用於從DataView中指定位元組偏移量開始檢索2位元組資料,檢索到的資料將被解碼為一個16位有符號整數。此方法還可以從資料檢視範圍內的任何偏移量獲取多位元組值。

如果我們不向此方法傳遞byteOffset引數,它將返回0,如果byteOffset引數超出資料檢視的範圍,它將丟擲一個'RangeError'異常。

語法

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

getInt16(byteOffset, littleEndian)

引數

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

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

返回值

此方法返回一個範圍在-3276832767(含)之間的整數。

示例 1

以下是JavaScript DataView getInt16()方法的基本示例。

<html>
<body>
<script>
   const buffer = new ArrayBuffer(16);
   const data_view = new DataView(buffer);
   const value = 32767;
   const byteOffset = 1;
   document.write("Value: ", value);
   document.write("<br>The byte offset: ", byteOffset);
   //storing the data
   data_view.setInt16(byteOffset, value);
   //using the getInt16() method
   document.write("<br>The store value: ",  data_view.getInt16(byteOffset));
</script>
</body>
</html>

輸出

上面提到的程式將返回已儲存的值。

Value: 32767
The byte offset: 1
The store value: 32767

示例 2

如果我們在此方法中傳遞byteOffset引數,它將返回0

以下是JavaScript DataView getInt16()方法的另一個示例,用於檢索2位元組資料值3405,該值由setInt16()方法在指定的位元組偏移量0處儲存。

<html>
<body>
<script>
   const buffer = new ArrayBuffer(16);
   const data_view = new DataView(buffer);
   const value = 3405;
   const byteOffset = 0;
   document.write("Value: ", value);
   document.write("<br>The byte offset: ", byteOffset);
   //using the getInt16() method
   data_view.getInt16(byteOffset, value);
   document.write("<br>The data_view.getInt16() method: ", data_view.getInt32());
</script>
</body>
</html>

輸出

執行上述程式後,它將返回0。

Value: 3405
The byte offset: 0
The data_view.getInt16() method: 0

示例 3

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

<html>
<body>
<script>
   const buffer = new ArrayBuffer(16);
   const data_view = new DataView(buffer);
   const value = 255;
   const byteOffset = 1;
   document.write("Value: ", value);
   document.write("<br>The byte offset: ", byteOffset);
   try {
      //using the getInt16(-1) method 
      data_view.getInt16(-1);
   } catch (error) {
      document.write("<br>", error);
   }
</script>
</body>
</html>

輸出

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

Value: 255
The byte offset: 1
RangeError: Offset is outside the bounds of the DataView
廣告