概念
定型数组所指的其实是一种特殊的包含数值类型的数组。方便我们将数据以二进制形式存到内存中,并提供读取方法
前置知识
ArrayBuffer
ArrayBuffer是所有定型数组及视图引用的基本单位
var buffer = new ArrayBuffer(2);
buffer.byteLength//2,buffer的字节数
var buffer1 = buffer.slice(1)//截取buffer
buffer1.byteLength//1
1、声明的ArrayBuffer会将所有二进制位初始为0
2、ArrayBuffer可以被垃圾回收,不需手动清除
ElementType
DataView
DataView是第一种操作ArrayView的工具
var buffer = new ArrayBuffer(2)
var view = new DataView(buffer);
view.byteOffset//0
view.byteLength//2
var view1 = new DataView(buffer,1,1);
view1.byteOffset//1
view1.byteLength//1
赋值和取值
var buffer = new ArrayBuffer(2)
var view = new DataView(buffer);
view.setUint8(0,1)
view.getUint8(0);//1
view.getUint8(1);//0
字节序
在取值和赋值方法中默认都是安照字节的正常顺序来的,而当我们最后一个参数指定为true就是倒着存,倒着取了
var buffer = new ArrayBuffer(2)
var view = new DataView(buffer);
view.setUint16(0,1)//00000000 00000001
view.getUint16(0,true)//(00000001 00000000)-> 256,字节序反了
view.setUint16(0,1,true)//00000001 00000000
view.getUint16(0,1)//256
溢出问题
var buffer = new ArrayBuffer(2)
var view = new DataView(buffer);
view.setUint8(0,256)
view.getUint8(0)//0,从低位数开始取,忽略超出的高位数
view.setUint8(2,1)//超出length,RangeError
定型数组
与DataView一样,定型数组也可以操作ArrayBuffer,但是它继承了Array中许多方法,可以更加方便的操作ArrayBuffer
var buffer = new ArrayBuffer(2)
var array = new Uint16Array(buffer)
console.log(array.length);//1
console.log(array.buffer===buffer);//true
var array1 = new Uint16Array(array)//分配新的缓存,深拷贝
var array2 = array.slice(0,1)//分配新的缓存,深拷贝
array = Uint16Array.of(1,2,3) //长度为3,值为1,2,3
array = Uint16Array.from([1,2,3]) //长度为3,值为1,2,3
array[0]//取值
array[0]=2//赋值
set方法
set方法用来在指定位置处填充数据
var buffer = new ArrayBuffer(4)
var array = new Uint16Array(buffer)
array.set([1,2],0)//[1,2]
subarray方法
subarray根据开始索引和结束索引返回定型数组的子数组
var buffer = new ArrayBuffer(4)
var array = new Uint16Array(buffer)
array.set([1,2],0)//[1,2]
var sub = array.subarray(0,1)//Uint16Array [1]
sub[0]=2
console.log(array)//Uint16Array [2,2],array随之改变
溢出问题
和DataView一样,从低位数开始取,忽略超出的高位数
Blob与ArrayBuffer的互相转换
var buffer = new ArrayBuffer(1);
var arrayBuffer = new Uint16Array([1,2])
var b = new Blob([buffer,arrayBuffer])//ArrayBuffer转换为Blob
console.log(b)//Blob {size: 5, type: ""}
var reader = new FileReader();
reader.onloadend = function(){
console.log(this.result)//ArrayBuffer(5)
}
reader.readAsArrayBuffer(b)//Blob转换为ArrayBuffer