What is the best way to populate a javascript typed array with literal data?
Recently I've been working a lot with javascript typed arrays for some mathematical work. In particular, I'm using lots of Float32Array objects.
I often have to manually populate their values. With a regular array, there is the following literal syntax available: var a = [0,1,2]; But there seems to be no equivalent way to populate a typed array, so I find I have to do it with lots of individual statements;
var a = new Float32Array(3);
a[0] = 0;
a[1] = 1;
a[2] = 2;
This gets very annoying if there's more than about 4 values. And it seems wasteful too, both in terms of script size, and javascript execution, because it has to interpret all those individual statements.
Another approach I've used is creating 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 seems quite wasteful too. I have to create a regular array as big as the typed array first, to feed into the populateArray function, and then there's the iteration.
So... the question is: Is there a more direct and efficient way to fill a typed array with literal data?