Comment fusionner TypedArrays en JavaScript?

Je voudrais fusionner plusieurs tableaux pour créer un bloc. Cependant, comme vous le savez, TypedArray n'a pas de méthodes "push" ou utiles …

Par exemple:

var a = new Int8Array( [ 1, 2, 3 ] ); var b = new Int8Array( [ 4, 5, 6 ] ); 

En conséquence, j'aimerais obtenir [ 1, 2, 3, 4, 5, 6 ] .

Utilisez la méthode set . Mais notez que vous avez besoin maintenant de deux fois la mémoire!

 var a = new Int8Array( [ 1, 2, 3 ] ); var b = new Int8Array( [ 4, 5, 6 ] ); var c = new Int8Array(a.length + b.length); c.set(a); c.set(b, a.length); console.log(a); console.log(b); console.log(c); 

J'utilise toujours cette fonction:

 function mergeTypedArrays(a, b) { // Checks for truthy values on both arrays if(!a && !b) throw 'Please specify valid arguments for parameters a and b.'; // Checks for truthy values or empty arrays on each argument // to avoid the unnecessary construction of a new array and // the type comparison if(!b || b.length === 0) return a; if(!a || a.length === 0) return b; // Make sure that both typed arrays are of the same type if(Object.prototype.toString.call(a) !== Object.prototype.toString.call(b)) throw 'The types of the two arguments passed for parameters a and b do not match.'; var c = new a.constructor(a.length + b.length); c.set(a); c.set(b, a.length); return c; } 

La fonction d'origine sans vérification de null ou de types

 function mergeTypedArraysUnsafe(a, b) { var c = new a.constructor(a.length + b.length); c.set(a); c.set(b, a.length); return c; }