JavaScript DataView getInt8() 方法在此 DataView 的指定字节偏移量处读取 1 字节数据,并将其解码为 8 位有符号整数。如果不指定该方法的 byteOffset 参数值,则始终返回 0。
如果 byteOffset 参数的值超出数据视图的边界,则此方法将引发 'RangeError' 异常。
语法
以下是 JavaScript DataView getInt8() 方法的语法 -
getInt8(byteOffset)
参数
此方法接受一个名为 'byteOffset' 的参数,如下所述 -
- byteOffset - DataView 中要从中读取数据的位置。
返回值
此方法返回一个介于 -128 到 127 之间(包括 -128 和 127)的有符号整数。
示例 1
以下示例演示了 JavaScript DataView getInt8() 方法的用法。
<html>
<body>
<script>
const buffer = new ArrayBuffer(16);
const data_view = new DataView(buffer);
const value = 127;
const byteOffset = 0;
document.write("Value: ", value);
document.write("<br>The byte offset: ", byteOffset);
//storing the data
data_view.setInt8(byteOffset, value);
//using the getInt8() method
document.write("<br>The stored value: ", data_view.getInt8(byteOffset));
</script>
</body>
</html>
输出
上面的程序将存储数据值返回为 −
Value: 127
The byte offset: 0
The stored value: 127
The byte offset: 0
The stored value: 127
示例 2
如果我们不将 byteOffset 参数传递给该方法,它将返回 0。
以下是 JavaScript DataView getInt8() 方法的另一个示例。我们使用该方法在指定的 byteOffset 1 处读取 1 个字节的数据值 40。由于我们没有将 byteOffset 参数传递给此方法,因此它将返回 0。
<html>
<body>
<script>
const buffer = new ArrayBuffer(8);
const data_view = new DataView(buffer);
const value = 40;
const byteOffset = 1;
document.write("Value: ", value);
document.write("<br>The byte offset: ", byteOffset);
//storing the data
data_view.setInt8(byteOffset, value);
//using the getInt8() method
document.write("<br>The data_view.getInt8() returns: ", data_view.getInt8());
</script>
</body>
</html>
输出
执行上述程序后,将返回 0。
Value: 40
The byte offset: 1
The data_view.getInt8() returns: 0
The byte offset: 1
The data_view.getInt8() returns: 0
示例 3
如果 byteOffset 参数超出此数据视图的边界,它将引发 'RangeError' 异常。
<html>
<body>
<script>
const buffer = new ArrayBuffer(8);
const data_view = new DataView(buffer);
const value = 121;
const byteOffset = 2;
document.write("Value: ", value);
document.write("<br>The byte offset: ", byteOffset);
//storing the data
data_view.setInt8(byteOffset, value);
try {
//using the getInt8() method
document.write("<br>The data_view.getInt8() returns: ", data_view.getInt8(-1));
} catch (error) {
document.write("<br>", error);
}
</script>
</body>
</html>
输出
一旦执行了上述程序,它将抛出一个 'RangeError' 异常,即 -
Value: 121
The byte offset: 2
RangeError: Offset is outside the bounds of the DataView
The byte offset: 2
RangeError: Offset is outside the bounds of the DataView