I have a JavaScript Float32Array, and I would like to convert it into a regular JavaScript Array. How can I do this?
-
1Why do you need it to be an Array?Eric– Eric2012-10-06 14:31:41 +00:00Commented Oct 6, 2012 at 14:31
-
2Note that the accepted answer works for all of the Javascript Typed Arrays, eg Int8Array, Float64Array, etc. Question title could be changed to reflect this, so it's more helpful for people searching for this answer.Daniel Howard– Daniel Howard2014-02-20 17:54:17 +00:00Commented Feb 20, 2014 at 17:54
-
I submitted a change proposal to the topic and question formulation.marcusstenbeck– marcusstenbeck2014-09-25 10:57:50 +00:00Commented Sep 25, 2014 at 10:57
-
One use case for this would be when you want to modify typed arrays with dat.GUIxeolabs– xeolabs2017-01-02 18:41:02 +00:00Commented Jan 2, 2017 at 18:41
4 Answers
If you don't need to support old browsers (including IE, unfortunately), you can use Array.from, which was added to ES6:
var array = Array.from(floatarr);
This now works in the new releases of every browser (except IE), and it works on all major mobile browsers too.
1 Comment
[...new Float32Array(16)].Use Array.prototype.slice to convert Float32Array to Array. jsfiddle
var floatarr = new Float32Array(12);
var array = Array.prototype.slice.call(floatarr);
3 Comments
floatarr is passed as this.You can use it as any array, which means you can do this :
var arr = [];
for (var i=0; i<myFloat32array.length; i++) arr[i] = myFloat32array[i];
But it's usually more efficient to use it as a Float32Array instead of converting it.
If you don't want to mix different types of values, don't convert it.
Comments
In one shot:
Object.prototype.toArray=Array.prototype.slice;
Then you can use it this way:
fa32 = new Float32Array([1.0010000467300415, 1.0019999742507935, 2.003000020980835]);
fa64 = new Float64Array([1.0010000467300415, 1.0019999742507935, 2.003000020980835]);
Object.prototype.toArray = Array.prototype.slice
console.log("fa32", fa32.toArray());
console.log("fa64", fa64.toArray());