Best way to populate a javascript array?

What is the best way to populate a javascript array with typed data?

I recently worked a lot with javascript based arrays for some math work. In particular, I use many Float32Array objects.

I often have to manually fill in their values. The following syntax is available with a regular array: var a = [0,1,2]; But there seems to be no equivalent way to populate a typed array, so I think I should do this with a lot of separate statements;

 var a = new Float32Array(3); a[0] = 0; a[1] = 1; a[2] = 2; 

This is very annoying if there are more than 4 values. And that seems wasteful, both in terms of script size and using javascript, because it has to interpret all these separate statements.

Another approach I used is to create a setter function:

 var populateArray(a,vals) { var N = vals.length; for (var i=0; i<N; i++) {a[i]=vals[i];} }; var a = new Float32Array(3); populateArray(a,[0,1,2]); 

But this is also quite wasteful. I must first create a regular array the size of a typed array in order to pass the populateArray function and then iterate.

So ... the question is: is there a more direct and efficient way to populate a typed array with literal data?

+6
source share
1 answer

Why not just make a new Float32Array([1,2,3]);

Look at the constructor overload :

Float32Array Float32Array (unsigned long length);

Float32Array Float32Array (TypedArray Array);

Float32Array Float32Array (array of sequences);

Float32Array Float32Array (Buffer ArrayBuffer, optional unsigned long byteOffset, Optional unsigned length);

+5
source

All Articles