betezed/html5wow

responseType = "arraybuffer" example has issues.

Closed this issue · 2 comments

that sample code on this slide is wrong

http://www.htmlfivewow.com/slide15


This ---


xhr.onload = function(e) {
  if (this.status == 200) {

    var uInt8Array = new Uint8Array(this.response); // Note: not xhr.responseText

    for (var i = 0, len = uInt8Array.length; i < len; ++i) {
      uInt8Array[i] = this.response[i];
    }

    var byte3 = uInt8Array[4]; // byte at offset 4
  }
};


should be this



xhr.onload = function(e) {
  if (this.status == 200) {

    var uInt8Array = new Uint8Array(this.response); // Note: not xhr.responseText
    var byte3 = uInt8Array[4]; // byte at offset 4
  }
};

1) There is no need to copy the data. Uint8Array is a "view" on to the 
arraybuffer
2) That code will FAIL. you can't index an ArrayBuffer 

Original issue reported on code.google.com by g...@greggman.com on 15 May 2011 at 9:34

Thanks Greg. I'll remove the for loop and commit. For some reason indexing like 
that into an ArrayBuffer
has worked in the past. Regardless, it's wasteful since you already have the 
buffer data.

Original comment by ericbidelman@chromium.org on 25 May 2011 at 6:12

  • Changed state: Fixed
I don't think it actually worked. I tried this in the JavaScript console

> a = new ArrayBuffer(3)
  ArrayBuffer
> a[0]
  undefined
> b = new Uint8Array(3)
  Uint8Array
> b[0] = 123
  123
> b[0] = a[0]
  undefined
> b[0]
  0

So all that loop did was clear the Uint8Array to 0



Original comment by g...@greggman.com on 25 May 2011 at 7:01