JavaScript DataView setFloat32() 方法用于在此数据视图中的起始字节偏移量处将 32 位浮点数存储在特定字节中。您可以在边界内的任何偏移量处存储多个字节值。
如果 byteOffset 参数的值超出此数据视图的边界,则此方法将引发 'RangeError' 异常。
语法
以下是 JavaScript DataView setFloat32() 方法的语法 -
setFloat32(byteOffset, value, littleEndian)
参数
此方法接受名为 'byteOffset'、'value' 和 'littleEndian' 的三个参数,如下所述 -
- byteOffset - DataView 中将存储字节的位置。
- value − 需要存储的 32 位浮点数。
- littleEndian − 它表示数据是以 little-endian 还是 big endian 格式存储。
返回值
此方法返回 'undefined',因为它只将字节值存储到 DataView。
示例 1
以下示例演示了 JavaScript DataView setFloat32() 方法的用法。
<html>
<body>
<script>
const buffer = new ArrayBuffer(16);
const data_view = new DataView(buffer);
const byteOffset = 0;
const value = 23432.342;
document.write("The byte offset: ", byteOffset);
document.write("<br>Value: ", value);
document.write("<br>The data_view.setFloat32() method returns: ", data_view.setFloat32(byteOffset, value));
</script>
</body>
</html>
输出
上面的程序返回 'undefined' -
The byte offset: 0
Value: 23432.342
The data_view.setFloat32() method returns: undefined
Value: 23432.342
The data_view.setFloat32() method returns: undefined
示例 2
以下是 JavaScript DataView setFloat32() 方法的另一个示例。我们使用此方法将 32 位浮点数 522453.23 存储在此 DataView 中从指定字节偏移量 1 开始的字节中。
<html>
<body>
<script>
const buffer = new ArrayBuffer(16);
const data_view = new DataView(buffer);
const byteOffset = 1;
const value = 522453.23;
document.write("The byte offset: ", byteOffset);
document.write("<br>Value: ", value);
//using setFloat32() method
data_view.setFloat32(byteOffset, value)
document.write("<br>The store value is: ", data_view.getFloat32(byteOffset));
</script>
</body>
</html>
输出
执行上述程序后,它会将浮点数存储在当前数据视图中,并将其显示为 -
The byte offset: 1
Value: 522453.23
The store value is: 522453.21875
Value: 522453.23
The store value is: 522453.21875
示例 3
如果 byteOffset 参数的值为 -1(超出边界),它将引发 'RangeError' 异常。
<html>
<body>
<script>
const buffer = new ArrayBuffer(16);
const data_view = new DataView(buffer);
const byteOffset = -1;
const value = 23322.422;
document.write("The byte offset: ", byteOffset);
document.write("<br>Value: ", value);
try {
//using setFloat32() method
data_view.setFloat32(byteOffset, value)
} catch (error) {
document.write("<br>", error);
}
</script>
</body>
</html>
输出
一旦执行了上述程序,它将抛出一个异常 -
The byte offset: -1
Value: 23322.422
RangeError: Offset is outside the bounds of the DataView
Value: 23322.422
RangeError: Offset is outside the bounds of the DataView