3

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...

KarenRei
  • 589
  • 6
  • 13
  • Well, I found a workaround, although I'd still like to know what was wrong (I have a DataBuffer for the whole ArrayBuffer, and I a getUint8 at i+4, a getUint16 at i+5, and then combine the two) – KarenRei Sep 30 '17 at 00:02
  • +1, I too am getting this "Invalid DataView length undefined" what not, even dumped on the console, and it's definitely not undefined. I'm thinking there's a Chrome bug... – Brad Oct 01 '17 at 04:45
  • This seems to be just a bad error message. The real error is that the **length would be outside the bounds** of the given ArrayBuffer. For example, `new DataView(new ArrayBuffer(3), 0, 4)` throws `Invalid DataView length undefined` in Chrome (in Safari, it throws `Length out of range of buffer`). – jtbandes Sep 20 '21 at 16:40

0 Answers0