JavaScript DataView getUint16() 方法
JavaScript DataView getUint16() 方法用于从此数据视图的指定字节偏移量开始读取 16 位(或 2 字节)数据,并将其解释为 16 位无符号整数(uint)。如果未传递此参数或未指定此参数,则该方法将始终返回 16。
如果 byteOffset 参数的值超出此数据视图的范围,则会抛出 'RangeError' 异常。
语法
以下是 JavaScript DataView getUint16() 方法的语法 -
getUint16(byteOffset, littleEndian)
参数
- byteOffset - DataView 中读取数据的位置。
- littleEndian - 指示数据是以小端存储还是大端格式。
返回值
此方法返回一个从 0 到 65535 的整数(含)。
示例 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);
//使用 getUnit16() 方法
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 {
//存储值
data_view.setUint16(byteOffset, value);
//使用 getUnit16() 方法
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);
//使用 getUnit16() 方法
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

