JavaScript DataView getUint16() 方法用于读取 16 位(或 2 字节)数据,从此数据视图的指定字节偏移量开始,并将其解释为 16 位无符号整数 (uint)。如果未向此方法传递或未指定此参数,则它将始终返回 16。
如果 byteOffset 参数的值超出此数据视图的边界,它将引发 'RangeError' 异常。
语法
以下是 JavaScript DataView getUint16() 方法的语法 -
getUint16(byteOffset, littleEndian)
参数
- byteOffset - DataView 中要从中读取数据的位置。
- littleEndian − 它指示数据是以 little-endian 还是 big-endian 格式存储。
返回值
此方法返回一个从 0 到 65535 的整数(包括 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);
//using the getUnit16() method
document.write("<br>The stored value: ", data_view.getUint16(byteOffset));
</script>
</body>
</html>
输出
上面的程序返回 read 值为 225。
The data value: 459
The byteOffset: 0
The stored 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
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
The byteOffset: 1
The data_view.getUnit16() method returns: 16