Tream Tream - 1 year ago 85
Javascript Question

JavaScript: How to separate a U8IntArray?

I have a U8IntArray with 20 bytes and I want to separate it into two parts (first 8 bytes and byte 9 to 20):

var arr = new Uint8Array( 20 );
var part1 = arr.slice( 0, 8 );
var part2 = arr.slice( 8 ); part1, part2 );

Works in FireFox, but fails in Chrome and Internet-Explorer:

TypeError: undefined is not a function*

Is there a easy way to slice the Uint8Array, which will work in all browsers?

Answer Source

The problem is that Typed Arrays were initially defined by the Typed Array Specification, which did not define any slice method in the TypedArray interface.

Now Typed Arrays are part of ECMAScript 6, but Internet Exporer don't support it completely.

So it will be safer to use only methods defined in the old spec. In this case, TypedArray.prototype.subarray should work since IE10.

var arr = new Uint8Array( 20 );
var part1 = arr.subarray( 0, 8 );
var part2 = arr.subarray( 8 ); part1, part2 );

Another alternative is using slice on the buffer instead of directly on the array, supported since IE11.

var arr = new Uint8Array( 20 );
var part1 = new Uint8Array( arr.buffer.slice( 0, 8 ) );
var part2 = new Uint8Array( arr.buffer.slice( 8 ) ); part1, part2 );

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download