JavaScript DataView getUint16() 方法用于读取 16 位(或 2 字节)数据,从此数据视图的指定字节偏移量开始,并将其解释为 16 位无符号整数 (uint)。如果未向此方法传递或未指定此参数,则它将始终返回 16。
如果 byteOffset 参数的值超出此数据视图的边界,它将引发 'RangeError' 异常。
语法
以下是 JavaScript DataView getUint16() 方法的语法 -
参数
- byteOffset - DataView 中要从中读取数据的位置。
- littleEndian − 它指示数据是以 little-endian 还是 big-endian 格式存储。
返回值
此方法返回一个从 0 到 65535 的整数(包括 0 到 65535)。
示例 1
在以下示例中,我们使用 JavaScript DataView getUint16() 方法读取 setUnit16() 方法在指定字节偏移量 0 处存储的值 459。
输出
上面的程序返回 read 值为 225。
The data value: 459
The byteOffset: 0
The stored value: 459
The byteOffset: 0
The stored value: 459
示例 2
如果 byteOffset 参数的值超出数据视图的边界,它将引发 'RangeError' 异常。
输出
执行上述程序后,它将抛出一个 '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 的结果。
输出
执行上述程序后,它将返回 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