JavaScript:如何分离U8IntArray? [英] JavaScript: How to separate a U8IntArray?

查看:106
本文介绍了JavaScript:如何分离U8IntArray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个20字节的U8IntArray,我想把它分成两部分(前8字节和字节9到20):

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 );

console.info( part1, part2 );

适用于FireFox,但在Chrome和Internet-Explorer中失败:

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


TypeError:undefined不是函数*

TypeError: undefined is not a function*

有没有简单的方法切片Uint8Array,它可以在所有浏览器中使用?

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

推荐答案

问题是Typed Arrays最初是由类型化数组规范,它没有在<$ c $中定义任何 slice 方法c> TypedArray interface。

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.

现在Typed Arrays是 ECMAScript 6 ,但Internet Exporer不完全支持它。

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

因此,仅使用旧规范中定义的方法会更安全。在这种情况下, TypedArray .prototype.subarray 自IE10起应该有效。

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 );
console.info( part1, part2 );

另一种选择是使用 slice 而不是直接在从IE11开始支持的数组。

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 ) );
console.info( part1, part2 );

这篇关于JavaScript:如何分离U8IntArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆