9

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?

1 Answer 1

6

Why not simply do new Float32Array([1,2,3]);

Look at the constructor overloads:

Float32Array Float32Array( unsigned long length );

Float32Array Float32Array( TypedArray array );

Float32Array Float32Array( sequence array );

Float32Array Float32Array( ArrayBuffer buffer, optional unsigned long byteOffset, optional unsigned long length );

Sign up to request clarification or add additional context in comments.

3 Comments

or, if the array is already declared, can also use a.set([1,2,3])
Wow - I didn't know you could do that! Unbelievably simple. I can't believe I haven't seen that before. Thank you so much!
@DanielHoward Np. Sometimes it's easier than you think ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.