JavaScript DataView getFloat32() 方法用于检索从此数据视图的指定字节偏移量开始的 4 字节浮点数,并将其解码为 32 位浮点数。您可以从边界内的任何偏移量获取多个字节值。
如果字节偏移量参数的值超出此数据视图的边界,则此方法将引发 'RangeError' 异常。
语法
以下是 JavaScript DataView getFloat32() 方法的语法 -
getFloat32(byteOffset, littleEndian)
参数
此方法接受两个名为 'byteOffset' 和 'littleEndian' 的参数,如下所述 -
- byteOffset - DataView 中要从中读取数据的位置。
- littleEndian (可选) − 它指示数据是存储在 little-endian 还是 big endian 中。
返回值
该方法返回 -3.4e38 到 3.4e38 范围内的整数。
示例 1
以下是 JavaScript DataView getFloat32() 方法的基本示例。
<html>
<body>
<script>
const buffer = new ArrayBuffer(16);
const data_view = new DataView(buffer);
const byteOffset = 0;
const value = Math.PI;
document.write("The byte offset: ", byteOffset);
document.write("<br>Value: ", value);
//storing the value
data_view.setFloat32(byteOffset, value);
document.write("<br>The stored value: ", data_view.getFloat32(byteOffset));
</script>
</body>
</html>
输出
上述程序将存储的值返回为“3.1415927410125732”。
The byte offset: 0
Value: 3.141592653589793
The stored value: 3.1415927410125732
Value: 3.141592653589793
The stored value: 3.1415927410125732
示例 2
如果 byteOffset 参数值超出此数据视图的边界,它将引发 'RangeError' 异常。
<html>
<body>
<script>
const buffer = new ArrayBuffer(16);
const data_view = new DataView(buffer);
const byteOffset = 1;
const value = 3.445323412;
document.write("The byte offset: ", byteOffset);
document.write("<br>Value: ", value);
//storing the value
data_view.setFloat32(byteOffset, value);
try {
document.write("<br>The stored value: ", data_view.getFloat32(-1));
} catch (error) {
document.write("<br>", error);
}
</script>
</body>
</html>
输出
执行完上面的程序后,会抛出一个异常 −
The byte offset: 1
Value: 3.445323412
RangeError: Offset is outside the bounds of the DataView
Value: 3.445323412
RangeError: Offset is outside the bounds of the DataView