JavaScript DataView getInt16() 方法用于检索从 DataView 中指定字节偏移量开始的 2 字节数据,检索到的数据将被解码为 16 位有符号整数。此方法还可以从边界内的任何偏移量中获取多字节值。
如果我们不将 byteOffset 参数传递给此方法,它将返回 0,如果 byteOffset 参数超出数据视图的边界,它将引发 'RangeError' 异常。
语法
以下是 JavaScript DataView getInt16() 方法的语法 -
getInt16(byteOffset, littleEndian)
参数
此方法接受两个名为 'byteOffset' 和 'littleEndian' 的参数,如下所述 -
- byteOffset - DataView 中要从中读取数据的位置。
- littleEndian - 它指示数据值是以 little-endian 还是 big-endian 格式存储。
返回值
此方法返回 -32768 到 32767 之间(包括 -32768 和 32767)的整数。
示例 1
以下是 JavaScript DataView getInt16() 方法的基本示例。
<html>
<body>
<script>
const buffer = new ArrayBuffer(16);
const data_view = new DataView(buffer);
const value = 32767;
const byteOffset = 1;
document.write("Value: ", value);
document.write("<br>The byte offset: ", byteOffset);
//storing the data
data_view.setInt16(byteOffset, value);
//using the getInt16() method
document.write("<br>The store value: ", data_view.getInt16(byteOffset));
</script>
</body>
</html>
输出
上面提到的程序将返回已存储的值。
Value: 32767
The byte offset: 1
The store value: 32767
The byte offset: 1
The store value: 32767
示例 2
如果我们在该方法中不传递 byteOffset 参数,它将返回 0。
以下是 JavaScript DataView getInt16() 方法的另一个示例,用于检索 2 字节数据值 3405,该值由 setInt16() 方法存储在指定的字节偏移量 0 处。
<html>
<body>
<script>
const buffer = new ArrayBuffer(16);
const data_view = new DataView(buffer);
const value = 3405;
const byteOffset = 0;
document.write("Value: ", value);
document.write("<br>The byte offset: ", byteOffset);
//using the getInt16() method
data_view.getInt16(byteOffset, value);
document.write("<br>The data_view.getInt16() method: ", data_view.getInt32());
</script>
</body>
</html>
输出
执行上述程序后,将返回 0。
Value: 3405
The byte offset: 0
The data_view.getInt16() method: 0
The byte offset: 0
The data_view.getInt16() method: 0
示例 3
如果 byteOffset 参数的值超出此数据视图的边界,它将引发 'RangeError' 异常。
<html>
<body>
<script>
const buffer = new ArrayBuffer(16);
const data_view = new DataView(buffer);
const value = 255;
const byteOffset = 1;
document.write("Value: ", value);
document.write("<br>The byte offset: ", byteOffset);
try {
//using the getInt16(-1) method
data_view.getInt16(-1);
} catch (error) {
document.write("<br>", error);
}
</script>
</body>
</html>
输出
执行上述程序后,它将引发 'RangeError' 异常。
Value: 255
The byte offset: 1
RangeError: Offset is outside the bounds of the DataView
The byte offset: 1
RangeError: Offset is outside the bounds of the DataView