Splitting an array of strings to an array of floats in JavaScript

心不动则不痛 提交于 2019-12-11 02:45:52

问题


I am trying to split an array of strings, called 'vertices' and store it as an array of floats.

Currently the array of strings contains three elemets: ["0 1 0", "1 -1 0", '-1 -1 0"]

What I need is an array of floats containing all these digits as individual elements: [0, 1, 0, 1, -1, 0, -1, -1, 0]

I used the split() function as follows:

for(y = 0; y < vertices.length; y++)
{
    vertices[y] = vertices[y].split(" "); 
}

...which gives me what looks to be what I am after except it is still made up of three arrays of strings.

How might I use parseFloat() with split() to ensure all elements are separate and of type float?


回答1:


You can use Array.prototype.reduce method for this:

var result = ["0 1 0", "1 -1 0", "-1 -1 0"].reduce(function(prev, curr) {
    return prev.concat(curr.split(' ').map(Number));
}, []);

alert(result); // [0, 1, 0, 1, -1, 0, -1, -1, 0]

Instead of .map(Number) you can use .map(parseFloat) of course if you need.

Or even shorter:

var result = ["0 1 0", "1 -1 0", "-1 -1 0"].join(' ').split(' ').map(Number);



回答2:


You could do something like this.

var res = []
for (var y = 0; y < vertices.length; y++) {
  var temp = vertices[y].split(" ");
  for (var i = 0; i < temp.length; i++) {
    res.push(parseFloat(temp[i]));
  }
}


来源:https://stackoverflow.com/questions/26978346/splitting-an-array-of-strings-to-an-array-of-floats-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!