美文网首页
ArrayBuffer常用操作

ArrayBuffer常用操作

作者: 风亡小窝 | 来源:发表于2020-02-20 17:39 被阅读0次

多个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

相关文章

网友评论

      本文标题:ArrayBuffer常用操作

      本文链接:https://www.haomeiwen.com/subject/minxqhtx.html