JavaScript DataView setInt32() 方法用于将数字值存储为 4 个字节的 32 位有符号整数,从此 DataView 的指定字节偏移量开始。可以在边界内的任何偏移量处存储多个字节。
如果指定的值不在 -2147483648 到 2147483647 的范围内,则不会将该值存储在此 DataView 中,如果 byteOffset 参数值超出此 DataView 的边界,则会引发 RangeError 异常。
语法
以下是 JavaScript DataView setInt32() 方法的语法 -
setInt32(byteOffset, value, littleEndian)
参数
此方法接受名为 'byteOffset'、'value' 和 'littleEndian' 的三个参数,如下所述 -
- byteOffset - DataView 中将存储字节的位置。
- value − 需要存储的有符号 32 位整数。
- littleEndian - 它指示数据值是以 little-endian 还是 big-endian 格式存储。
返回值
此方法返回 'undefined'。
示例 1
以下是 JavaScript DataView setInt32() 方法的基本示例。
<html>
<body>
<script>
const buffer = new ArrayBuffer(16);
const data_view = new DataView(buffer);
const value = 200;
const byteOffset = 0;
document.write("Value: ", value);
document.write("<br>The byte offset: ", byteOffset);
//using the setInt32() method
document.write("<br>The data_view.setInt32() method returns: ", data_view.setInt32(byteOffset, value));
</script>
</body>
</html>
输出
上面的程序返回 'undefined' -
Value: 200
The byte offset: 0
The data_view.setInt32() method returns: undefined
The byte offset: 0
The data_view.setInt32() method returns: undefined
示例 2
如果数据值超出 -2147483648 到 2147483647 的范围,则 setInt8() 方法将不会存储指定的值,因为它超出了 8 位有符号整数的范围。
<html>
<head>
<title>JavaScript DataView setInt32() Method</title>
</head>
<body>
<script>
const buffer = new ArrayBuffer(16);
const data_view = new DataView(buffer);
const value = 21474836478;
const byteOffset = 1;
document.write("Value: ", value);
document.write("<br>The byte offset: ", byteOffset);
//using the setInt32() method
data_view.setInt32(byteOffset, value);
document.write("<br>The store value: ", data_view.getInt32(1));
</script>
</body>
</html>
输出
执行程序后,数据值将不会被存储,因为它超出了可接受值的范围 -
Value: 21474836478
The byte offset: 1
The store value: -2
The byte offset: 1
The store value: -2
示例 3
如果 byteOffset 参数的值超出此数据视图的边界,它将引发 'RangeError' 异常。
<html>
<body>
<script>
const buffer = new ArrayBuffer(16);
const data_view = new DataView(buffer);
const value = 243;
const byteOffset = -1;
document.write("Value: ", value);
document.write("<br>The byte offset: ", byteOffset);
try {
//using the setInt32() method
data_view.setInt32(byteOffset, value);
} catch (error) {
document.write("<br>", error);
}
</script>
</body>
</html>
输出
执行上述程序后,它将引发 'RangeError' 异常。
Value: 243
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