JavaScript DataView setUint16() 方法



JavaScript DataView 的 setUint16() 方法用于将指定的数字存储为从指定 字节偏移量 开始的 2 个字节中的 16 位(1 字节 = 8 位)无符号整数。

如果 byteOffset 参数的值超出此数据视图的范围,或者您没有将此参数传递给 setUint16() 方法,它将抛出 'RangeError' 异常。

语法

以下是 JavaScript DataView setUint16() 方法的语法:

setUint16(byteOffset, value, littleEndian)

参数

此方法接受三个名为 'byteOffset'、'value' 和 'littleEndian' 的参数,如下所述:

  • byteOffset - 数据视图中将存储字节的位置。
  • value - 需要存储的无符号 16 位整数。
  • littleEndian (可选) - 它指示数据是以小端序还是大端序格式存储。

返回值

此方法返回 undefined

示例 1

以下程序演示了 JavaScript DataView setUnit16() 方法的使用。

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

输出

上述程序返回存储的值为 225。

The data value: 255
The byteOffset: 1
The stored value: 255

示例 2

如果 byteOffset 参数的值超出 DataView 的范围,则会抛出 'RangeError' 异常。

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

输出

执行上述程序后,它将抛出 'RangeError' 异常。

The data value: 30
The byteOffset: 17
RangeError: Offset is outside the bounds of the DataView

示例 3

如果您没有将 byteOffset 参数传递给此方法,它将抛出 'RangeError' 异常。

<html>
<body>
<script>
   const buffer = new ArrayBuffer(16);
   const data_view = new DataView(buffer);
   const value = 200;
   const byteOffset = 1;
   document.write("The data value: ", value);
   document.write("<br>The byteOffset: ", byteOffset);
   //using the setUnit16() method
   try {
      //not passing byteOffset parameter
      data_view.setUint16(value);
   }catch (error) {
      document.write("<br>", error);
   }
</script>
</body>
</html>

输出

执行上述程序后,它将抛出 'RangeError' 异常。

The data value: 200
The byteOffset: 1
RangeError: Offset is outside the bounds of the DataView
广告

© . All rights reserved.