Splitting an array of strings to an array of float

2019-07-17 08:54发布

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?

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-07-17 09:34

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);
查看更多
淡お忘
3楼-- · 2019-07-17 09:52

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

查看更多
登录 后发表回答