How can I merge TypedArrays in JavaScript?

后端 未结 7 485
说谎
说谎 2020-12-09 01:01

I\'d like to merge multiple arraybuffers to create a Blob. however, as you know, TypedArray dosen\'t have \"push\" or useful methods...

E.g.:

var a          


        
7条回答
  •  清歌不尽
    2020-12-09 01:34

    if I have multiple typed arrays

                arrays = [ typed_array1, typed_array2,..... typed_array100]
    

    I want concat all 1 to 100 sub array into single 'result' this function works for me.

      single_array = concat(arrays)
    
    
    function concat(arrays) {
      // sum of individual array lengths
      let totalLength = arrays.reduce((acc, value) => acc + value.length, 0);
    
      if (!arrays.length) return null;
    
       let result = new Uint8Array(totalLength);
    
          // for each array - copy it over result
          // next array is copied right after the previous one
          let length = 0;
          for(let array of arrays) {
                result.set(array, length);
                length += array.length;
          }
    
          return result;
       }
    

提交回复
热议问题