JavaScript DataView getUint16() 方法



JavaScript DataView 的 getUint16() 方法用於讀取從資料檢視指定位元組偏移量開始的 16 位(或 2 位元組)資料,並將它們解釋為 16 位無符號整數 (uint)。如果未傳遞或未指定此引數給此方法,它將始終返回 16

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

語法

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

getUint16(byteOffset, littleEndian)

引數

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

返回值

此方法返回一個介於 065535(含)之間的整數。

示例 1

在以下示例中,我們使用 JavaScript DataView 的 getUint16() 方法讀取由 setUnit16() 方法在指定位元組偏移量 0 處儲存的值 459。

<html>
<body>
<script>
   const buffer = new ArrayBuffer(16);
   const data_view = new DataView(buffer);
   const value = 459;
   const byteOffset = 0;
   document.write("The data value: ", value);
   document.write("<br>The byteOffset: ", byteOffset);
   //storing the value
   data_view.setUint16(byteOffset, value);
   //using the getUnit16() method
   document.write("<br>The stored value: ", data_view.getUint16(byteOffset));
</script>
</body>
</html>

輸出

上述程式將讀取的值作為 225 返回。

The data value: 459
The byteOffset: 0
The stored value: 459

示例 2

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

<html>
<body>
<script>
   const buffer = new ArrayBuffer(16);
   const data_view = new DataView(buffer);
   const value = 300;
   const byteOffset = 1;
   document.write("The data value: ", value);
   document.write("<br>The byteOffset: ", byteOffset);
   try {
      //storing value
      data_view.setUint16(byteOffset, value);
	  //using the getUnit16() method
      document.write("<br>The stored value: ", data_view.getUint16(-1));
   }catch (error) {
      document.write("<br>", error);
   }
</script>
</body>
</html>

輸出

執行上述程式後,將丟擲 'RangeError' 異常,如下所示:

The data value: 300
The byteOffset: 1
RangeError: Offset is outside the bounds of the DataView

示例 3

如果未將 byteOffset 引數傳遞給此方法,它將返回結果 16

<html>
<body>
<script>
   const buffer = new ArrayBuffer(16);
   const data_view = new DataView(buffer);
   const value = 4234;
   const byteOffset = 1;
   document.write("The data value: ", value);
   document.write("<br>The byteOffset: ", byteOffset);
   data_view.setUint16(byteOffset, value);
   //using the getUnit16() method
   document.write("<br>The data_view.getUnit16() method returns: ", data_view.getUint16());//not passing byteOffset
</script>
</body>
</html>

輸出

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

The data value: 4234
The byteOffset: 1
The data_view.getUnit16() method returns: 16
廣告