Force Javascript array to Float32

Viewed 267

I'm working with WebGL, so I need Float32Arrays all the time. Is there a way to force an array to be a Float32Array? I tried this:

var cubeVertices = new Float32Array(3 * 4 * 6);
cubeVertices = [
   /* Vertices */
];

But this appears to change the type to a Float64Array, since I can't use it with WebGL, but it works when I do a new Float32Array(cubeVertices). I don't really want to use the new Float32Array command all the time, since it allocates memory that is of no use, because I don't need several copies of my data.

So is there a way of creating a Float32Array without having two arrays, where one is never used again?

4 Answers

There are only 3 ways to create the actual Float32Array:

  • new Float32Array(length)
  • TypedArray.from(source[, mapFn[, thisArg]]) source
  • TypedArray.of(element0[, element1[, ...[, elementN]]]) source

I think this will be correct for you.

var num=[6676.88,8878.99.....];
var floatVal=num.map(function(value){
     return Math.fround(value);
});
console.log(floatVal);

So I kind of created my own solution out of these answers, so that there aren't two arrays wasting memory. I use the Float32Array.from function and create a local array there that should be deleted after that line, so my code looks like this:

var cubeVertices = Float32Array.from(
  [
     0.5, -0.5, -0.5,
    -0.5, -0.5, -0.5,
     0.5,  0.5, -0.5,
    -0.5,  0.5, -0.5
  ]
);

Thanks to Akxe, using Float32Array.of would be even better, but it is not very widely supported.

Related