简体   繁体   English

在JavaScript中将字符串数组拆分为浮点数组

[英]Splitting an array of strings to an array of floats in JavaScript

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"] 目前,字符串数组包含三个元素: ["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] 我需要的是一个包含所有这些数字作为单个元素的浮点数组: [0, 1, 0, 1, -1, 0, -1, -1, 0]

I used the split() function as follows: 我使用了split()函数,如下所示:

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? 我如何将split()与parseFloat()一起使用以确保所有元素都是单独的并且类型为float?

You can use Array.prototype.reduce method for this: 您可以使用Array.prototype.reduce方法:

 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. 如果需要,您可以使用.map(parseFloat)代替.map(Number)

Or even shorter: 甚至更短:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM