JavaScript DataView setUint16() 方法用于将指定数字存储为 16 位(1 字节 = 8 位)无符号整数,该整数位于从此数据视图的指定字节偏移量开始的 2 个字节中。
如果 byteOffset 参数的值超出此数据视图的边界,或者您尚未将此参数传递给 setUint16() 方法,它将引发 'RangeError' 异常。
语法
以下是 JavaScript DataView setUint16() 方法的语法 -
setUint16(byteOffset, value, littleEndian)
参数
此方法接受名为 'byteOffset'、'value' 和 'littleEndian' 的三个参数,如下所述 -
- byteOffset - DataView 中将存储字节的位置。
- value − 需要存储的无符号 16 位整数。
- littleEndian(可选)− 它指示数据是以 little-endian 还是 big-endian 格式存储。
返回值
此方法返回 undefined。
示例 1
下面的程序演示了 JavaScript DataView setUnit16() 方法的用法。
<html>
<body>
<script>
const buffer = new ArrayBuffer(16);
const data_view = new DataView(buffer);
const value = 255;
const byteOffset = 1;
document.write("The data value: ", value);
document.write("<br>The byteOffset: ", byteOffset);
//using the setUnit16() method
data_view.setUint16(byteOffset, value);
document.write("<br>The stored value: ", data_view.getUint16(1));
</script>
</body>
</html>
输出
上述程序返回 store 值为 225。
The data value: 255
The byteOffset: 1
The stored value: 255
The byteOffset: 1
The stored value: 255
示例 2
如果 byteOffset 参数的值超出 DataView 的边界,则会引发 'RangeError' 异常。
<html>
<body>
<script>
const buffer = new ArrayBuffer(16);
const data_view = new DataView(buffer);
const value = 30;
const byteOffset = 17;
document.write("The data value: ", value);
document.write("<br>The byteOffset: ", byteOffset);
//using the setUnit16() method
try {
data_view.setUint16(byteOffset, value);
document.write("<br>The stored value: ", data_view.getUint16(1));
}catch (error) {
document.write("<br>", error);
}
</script>
</body>
</html>
输出
执行上述程序后,将抛出 RangeError 异常。
The data value: 30
The byteOffset: 17
RangeError: Offset is outside the bounds of the DataView
The byteOffset: 17
RangeError: Offset is outside the bounds of the DataView
示例 3
如果不将 byteOffset 参数传递给此方法,它将引发 'RangeError' 异常。
<html>
<body>
<script>
const buffer = new ArrayBuffer(16);
const data_view = new DataView(buffer);
const value = 200;
const byteOffset = 1;
document.write("The data value: ", value);
document.write("<br>The byteOffset: ", byteOffset);
//using the setUnit16() method
try {
//not passing byteOffset parameter
data_view.setUint16(value);
}catch (error) {
document.write("<br>", error);
}
</script>
</body>
</html>
输出
执行上述程序后,它将引发 'RangeError' 异常。
The data value: 200
The byteOffset: 1
RangeError: Offset is outside the bounds of the DataView
The byteOffset: 1
RangeError: Offset is outside the bounds of the DataView

