javascript 的Uint8Array 构造函数对 typedArray的引用问题

javascript 的 Uint8Array 支持字节数据,对于操作二进制数据非常有用,笔者初次接触时发现它有几个构造函数,如下:

new Uint8Array(); 
new Uint8Array(length);
new Uint8Array(typedArray);
new Uint8Array(object);
new Uint8Array(buffer [, byteOffset [, length]]);

        这些函数都返回一个Uint8Array类型的对象,但对于 new Uint8Array(typedArray); 这个形式的构造函数需要理解一下。在MDN的官方文档里描述不详, new Uint8Array(typedArray) 表示根据typedArray提供的对象创建一个Uint8Array对象,并保持对typedArray对象的引用, 这个形式的构造函数不会复制typedArray对象的。

        尝试以下代码,看看输出结果。

// create a TypedArray with a size in bytes
var buffer = new ArrayBuffer(8);

var typedArray1 = new Uint8Array(buffer);
typedArray1[0] = 32;
typedArray1[1] = 33;
typedArray1[2] = 34;

var typedArray2 = new Uint8Array(buffer);
typedArray2[0] = 42;
typedArray2[1] = 43;
typedArray2[2] = 44;

console.log(typedArray1);
//不是输出 Uint8Array [32, 33, 34, 0, 0, 0, 0, 0]
//正确输出 Uint8Array [42, 43, 44, 0, 0, 0, 0, 0]

console.log(typedArray2);
//正确输出 Uint8Array [42, 43, 44, 0, 0, 0, 0, 0]

从以上代码看到了 typedArray1 与 typedArray2 输出完全一样。原因就是 typedArray1.buffer 与 typedArray2.buffer 指向的是同一个对象,因此分别修改typedArray1 与 typedArray2时,实际上修改的是同一内存对象。

When creating an instance of a TypedArray (e.g. Int8Array), an array buffer is created internally in memory or, if an ArrayBuffer object is given as constructor argument, then this is used instead.  The buffer address is saved as an internal property of the instance and all the methods of %TypedArray%.prototype, i.e. set value and get value etc., operate on that array buffer address.

因此,用 ArrayBuffer 作为构造函数的参数时,Uint8Array直接引用这个ArrayBuffer对象作为内部缓冲,而不再创建内部 ArrayBuffer对象。

ArrayBuffer

ArrayBuffer 对象用来表示通用的原始二进制数据缓冲区。类似于C语言的 void * 类型的缓冲区。它没有任何类型,它是一个字节数组,通常在其他语言中称为“byte array”。不能直接操作 ArrayBuffer 中的内容;而是要通过类型化数组对象(TypedArray的子类)或 DataView 对象来操作,它们会将缓冲区中的数据表示为特定的格式(类似于C语言将缓冲区指针强制类型转换),并通过这些格式来读写缓冲区的内容。

ArrayBuffer() 构造函数创建一个以字节为单位的给定长度的新 ArrayBuffer。你也可以从现有的数据(例如,从 Base64 字符串或者从本地文件)获取数组缓冲区。

ArrayBuffer 是一个可转移对象。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值