当我在控制台中执行svg.getAttribute(" d")时,我有一串数字:
" -0.05990783410138251,0.13594470046082952,-0.06912442396313362,0.14976958525345618,-0.07603686635944701,0.15668202764976957,-0.08755760368663595,0.16589861751152069,-0.09677419354838718,0.16820276497695852,-0.10599078341013829,0.16820276497695852,-0.12211981566820279,0.16820276497695852,-0.13594470046082957,0.16820276497695852,-0.14055299539170513, 0.16820276497695852,-0.14516129032258068,0.16589861751152069,-0.1474654377880184"
我希望将其转换为浮点数,所以我做了parseFloat(svg.getAttribute(" d"))但我得到的只是第一个数字:
-0.05990783410138251
我如何获得所有数字?
由于
答案 0 :(得分:2)
使用String.prototype.split()
和Array.prototype.map()
,您可以获得一系列浮点值,如下所示:
const values = '-0.05990783410138251,0.13594470046082952,-0.06912442396313362,0.14976958525345618,-0.07603686635944701,0.15668202764976957,-0.08755760368663595,0.16589861751152069,-0.09677419354838718,0.16820276497695852,-0.10599078341013829,0.16820276497695852,-0.12211981566820279,0.16820276497695852,-0.13594470046082957,0.16820276497695852,-0.14055299539170513,0.16820276497695852,-0.14516129032258068,0.16589861751152069,-0.1474654377880184';
const floats = values.split(',').map(parseFloat);
console.log(floats);
答案 1 :(得分:1)
您可以先使用split()
功能将字符串拆分为','然后可以应用parseFloat()
。
答案 2 :(得分:0)
首先需要将其转换为字符串数组,然后您可以单独解析每个字符串。像这样:
var str = svg.getAttribute("d");
var strNums = str.split(',');
var nums = strNums.map(function (num) {
return parseFloat(num);
});
答案 3 :(得分:0)
const numArray = thatStringOfNumbers.split(',').map((num) => parseFloat(num))