JavaScript DataView setUint32() 方法将值存储为 32 位(1 字节 = 8 位)无符号整数,从此数据视图的指定字节偏移量开始,以 4 个字节为单位。
如果字节偏移量超出此 DataView 的边界,则会引发 'RangeError' 异常。
语法
以下是 JavaScript DataView setUint32() 方法的语法 -
setUint32(byteOffset, value, littleEndian)
参数
此方法接受名为 'byteOffset'、'value' 和 'littleEndian' 的三个参数,如下所述 -
- byteOffset - DataView 中将存储字节的位置。
- value - 需要存储的无符号 32 位整数。
- littleEndian(可选)− 它指示数据是以 little-endian 还是 big-endian 格式存储。
返回值
此方法返回 undefined,因为它只存储 byte 值。
示例 1
以下是 JavaScript DataView setUint32() 方法的基本示例。
<html>
<body>
<script>
const buffer = new ArrayBuffer(16);
const data_view = new DataView(buffer);
const value = 20;
const byteOffset = 0;
document.write("The data value: ", value);
document.write("<br>The byteOffset: ", byteOffset);
document.write("<br>The setUnit32() method returns: ", data_view.setUint32(byteOffset, value));
</script>
</body>
</html>
输出
上面的程序返回 'undefined'。
The data value: 20
The byteOffset: 0
The setUnit32() method returns: undefined
The byteOffset: 0
The setUnit32() method returns: undefined
示例 2
如果 byteOffset 参数值超出此 DataView 的边界,它将引发 'RangeError' 异常。
<html>
<body>
<script>
const buffer = new ArrayBuffer(16);
const data_view = new DataView(buffer);
const value = 24;
const byteOffset = -1;
document.write("The data value: ", value);
document.write("<br>The byteOffset: ", byteOffset);
try {
data_view.setUint32(byteOffset, value);
} catch (error) {
document.write("<br>Error: " + error);
}
</script>
</body>
</html>
输出
执行完上述程序后,会抛出一个异常 -
The data value: 24
The byteOffset: -1
Error: RangeError: Offset is outside the bounds of the DataView
The byteOffset: -1
Error: RangeError: Offset is outside the bounds of the DataView