Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
DataView is a view into an ArrayBuffer, like Typed Arrays, but in this case the items in the array can have different sizes and types.
Here’s an example:
const buffer = new ArrayBuffer(64)
const view = new DataView(buffer)
Since this is a view over a buffer, we can specify which byte we want to start from, and the length:
const view = new DataView(buffer, 10) // start at byte 10
const view = new DataView(buffer, 10, 30) // start at byte 10, length 30 bytes
If we don’t add those additional arguments, the view starts at position 0 and loads all the bytes present in the buffer.
There is a set of methods we can use to add data into the buffer:
setInt8()setInt16()setInt32()setUint8()setUint16()setUint32()setFloat32()setFloat64()
This is how to call one of those methods:
const buffer = new ArrayBuffer(64)
const view = new DataView(buffer)
view.setInt16(0, 2019)
By default data is stored in big endian. You can use little endian by passing true as a third parameter:
const buffer = new ArrayBuffer(64)
const view = new DataView(buffer)
view.setInt16(0, 2019, true)
Here is how we can get data from the view:
getInt8()getInt16()getInt32()getUint8()getUint16()getUint32()getFloat32()getFloat64()
Example:
const buffer = new ArrayBuffer(64)
const view = new DataView(buffer)
view.setInt16(0, 2019)
view.getInt16(0) //2019
Since a DataView is an ArrayBufferView, we have those 3 read-only properties:
bufferpoints to the original ArrayBufferbyteOffsetis the offset on that bufferbyteLengthis the length of its content in bytes
Unlike Typed Arrays, DataView lets you control the endianness when reading or writing, so you can correctly handle data from systems that use a different byte order.
In case you need this kind of control, DataView is the right choice.
Lessons in this unit:
| 0: | Introduction |
| 1: | ArrayBuffer |
| 2: | ArrayBufferView |
| 3: | Typed Arrays |
| 4: | ▶︎ DataView |
| 5: | Data URLs |