JavaScript ArrayBuffer slice apparently broken in

2019-07-06 11:53发布

问题:

A basic JavaScript function seems to be broken in Safari 9.1.2 (10601.7.7). Perhaps I am just doing something wrong? Looking for advice on how to work past this...

The function in question is ArrayBuffer.prototype.slice()

Here's a usage example that works fine in Chrome and Firefox, but not in Safari.

var buffer = new ArrayBuffer(16);
var bufferView = new Uint8Array(buffer);
console.log(bufferView.slice(0,8)); // TypeError: bufferView.slice is not a function

回答1:

I'm just writing this out as an answer, all the relevant facts were in comments already (thus community wiki).

You're calling .slice() on the Uint8Array object, not on the ArrayBuffer, and .slice() is not supported on typed arrays in Safari and Internet Explorer.

Instead, you can use bufferView.buffer.slice(), or this helper method written by Patch:

if(!Uint8Array.prototype.slice)
{
    Uint8Array.prototype.slice = function(a,b){
        var Uint8ArraySlice = new Uint8Array(this.buffer.slice(a,b));
        return Uint8ArraySlice;
    }
}