DataView
udostępnia niskopoziowy interfejs do zapisu i odczytu typów numerycznych w formie ArrayBuffer
niezależnie od kodowania platformy.
Składnia
new DataView(buffer [, byteOffset [, byteLength]])
Parametry
buffer
- Istniejący
ArrayBuffer
lubSharedArrayBuffer
używany jako pamięć dla obiektuDataView
. byteOffset
Optional- The offset, in bytes, to the first byte in the specified buffer for the new view to reference. If not specified, the view of the buffer will start with the first byte.
byteLength
Optional- The number of elements in the byte array. If unspecified, length of the view will match the buffer's length.
Return value
A new DataView
object representing the specified data buffer.
Exceptions
RangeError
- Thrown if the
byteOffset
andbyteLength
result in the specified view extending past the end of the buffer.
Description
Endianness
Multi-byte number formats are represented in memory differently depending on machine architecture, see Endianness for an explanation. DataView accessors provide explicit control of how data will be accessed irrespective of the platform architecture's endianness.
var littleEndian = (function() {
var buffer = new ArrayBuffer(2);
new DataView(buffer).setInt16(0, 256, true /* littleEndian */);
// Int16Array uses the platform's endianness.
return new Int16Array(buffer)[0] === 256;
})();
console.log(littleEndian); // true or false
Properties
All DataView
instances inherit from DataView.prototype
and allows the addition of properties to all DataView objects.
{{page('en-US/Web/JavaScript/Reference/Global_Objects/DataView/prototype','Properties')}}
Methods
{{page('en-US/Web/JavaScript/Reference/Global_Objects/DataView/prototype','Methods')}}
Example
var buffer = new ArrayBuffer(16);
var dv = new DataView(buffer, 0);
dv.setInt16(1, 42);
dv.getInt16(1); //42
Specifications
Specification | Status | Comment |
---|---|---|
Typed Array Specification | Obsolete | Superseded by ECMAScript 6 |
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'DataView' in that specification. |
Standard | Initial definition in an ECMA standard |
ECMAScript (ECMA-262) The definition of 'DataView' in that specification. |
Living Standard |
Browser compatibility
BCD tables only load in the browser
Compatibility notes
Starting with Firefox 40, DataView
requires to be constructed with a new
operator. Calling DataView()
as a function without new
, will throw a TypeError
from now on.
var dv = DataView(buffer, 0);
// TypeError: calling a builtin DataView constructor without new is forbidden
var dv = new DataView(buffer, 0);
See also
- jDataView: JavaScript library that polyfills and extends the
DataView
API to all browsers and Node.js. ArrayBuffer
SharedArrayBuffer