多个ArrayBuffer合并
//arrays成员类型可以是 ArrayBuffer 或 TypeArray
function mergeArrayBuffer(...arrays) {
let totalLen = 0
for (let i = 0; i < arrays.length; i++) {
arrays[i] = new Uint8Array(arrays[i]) //全部转成Uint8Array
totalLen += arrays[i].length
}
let res = new Uint8Array(totalLen)
let offset = 0
for(let arr of arrays) {
res.set(arr, offset)
offset += arr.length
}
return res.buffer
}
字符串转ArrayBuffer
let enc = new TextEncoder()
let data = enc.encode("ABCD")
console.log(data)
//打印结果
//Uint8Array(4) [65, 66, 67, 68]
参考链接
DataView
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/DataView
ArrayBuffer
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
TypeArray
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
网友评论