Splitting an array of strings to an array of float

2019-07-17 09:25发布

问题:

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]));
  }
}