Totally not getting something about ArrayBuffers and DataViews.

Viewed 844

Here's what I'm trying to do (trying to convert the upper 3 bytes of a little endian number at a point in an ArrayBuffer into the number itself):

var tmp = new DataView("\0" + array_buffer.slice(i+4, i+7), 0, 4).getUint32(0, true);

This fails with:

(index):415 Uncaught TypeError: First argument to DataView constructor must be an ArrayBuffer

Okay, it must be making it into a string then? So let's try:

var tmp = new DataView(new ArrayBuffer("\0" + array_buffer.slice(i+4, i+7)), 0, 4).getUint32(0, true);

This gives:

Uncaught RangeError: Invalid DataView length undefined

Indeed, even I get the same thing if I leave off the "\0" + :

var tmp = new DataView(array_buffer.slice(i+4, i+7), 0, 4).getUint32(0, true);

Result:

Uncaught RangeError: Invalid DataView length undefined

So I tried some test code to see if I could find a workaround:

var tmpp = new ArrayBuffer("0123456789");
alert(tmpp.slice(3, 6).toString());
alert(tmpp.slice(3, 6).toString().length);

This yields:

[object ArrayBuffer]
20

I'm baffled. Even with toString it's still an ArrayBuffer? But DataView insists I'm not passing an ArrayBuffer? But when I create a new ArrayBuffer it says the length is undefined, even though I specified a fixed-length slice? And when I do toString and print out the length, it comes out as 20, even though the slice was only 3 long?

There's something I'm really not understanding here...

0 Answers
Related