在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.
当前字符串数组包含三个元素:["0 1 0", "1 -1 0", '-1 -1 0"]
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]
我按如下方式使用split()函数:
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.
如何将parseFloat()与split()结合使用,以确保所有元素都是独立的且类型为float?
How might I use parseFloat() with split() to ensure all elements are separate and of type float?
推荐答案
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]
如果需要,您当然可以使用.map(parseFloat)
代替.map(Number)
.
Instead of .map(Number)
you can use .map(parseFloat)
of course if you need.
或更短:
var result = ["0 1 0", "1 -1 0", "-1 -1 0"].join(' ').split(' ').map(Number);
这篇关于在JavaScript中将字符串数组拆分为浮点数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!