在控制台中执行svg.getAttribute(“ d”)时,我有一串数字:

“-0.05990783410138251,0.13594470046082952,-0.06912442396313362,0.14976958525345618,-0.07603686635944701,0.15668202764976957,-0.0875576​​0368663595,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

我如何获得所有数字?

谢谢

最佳答案

使用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);

09-11 17:42