【问题标题】:Javascript convert a list of string coords into two float lists of Lat/Lng coords?Javascript 将字符串坐标列表转换为 Lat/Lng 坐标的两个浮点列表?
【发布时间】:2020-07-29 18:10:38
【问题描述】:

这是我目前拥有的:

var coords1 = ["52.535614,-7.285257", "52.571321,-1.585436", "53.535614,-2.285257"];

这是我的目标:

lat1 = [52.535614, 52.571321, 53.535614]
lng1 = [-7.285257, -1.585436, -2.285257]

我知道如何单独做:

a = coords1[0]
b = a.split(',');
c = b[0];
d = b[1];

e = Number(c);
f = Number(d);
>> 52.535614
>> -7.285257

我可以将这些附加到单独的列表中,但我假设这不是一种非常有效的方法,并且想知道如何使用几乎无限的坐标列表来做到这一点。

【问题讨论】:

  • const parts = coords1.map(s => s.split(",").map(Number)); 然后const lat1 = parts.map(a => a[0])

标签: javascript arrays list


【解决方案1】:

您可以拆分和映射数字并推送到相关数组。

var coords = ["52.535614,-7.285257", "52.571321,-1.585436", "53.535614,-2.285257"],
    lat = [],
    lng = [];

coords.forEach(s => s
    .split(',')
    .map(Number)
    .forEach((v, i) => [lat, lng][i].push(v))
);

console.log(lat);
console.log(lng);

【讨论】:

    【解决方案2】:

    只需一个循环即可完成。对于这种方式,您需要使用 reducerestslice

    const coords1 = ["52.535614,-7.285257", "52.571321,-1.585436", "53.535614,-2.285257"];
    
    const [firstCoord, secondCoord] = coords1.reduce((acc, rec) => {  // use rest parametr
      const comma = rec.indexOf(',') // find index of comma
      return [ 
      ...acc, // copy accamulator of reduce
        acc[0].push(rec.slice(0, comma)), // get first part of string
        acc[1].push(rec.slice(comma + 1, rec.length)) // get second part of string
      ]
    }, [[], []]) // special initial value
    
    console.log(firstCoord)
    console.log(secondCoord)

    【讨论】:

      猜你喜欢
      • 2022-11-17
      • 2022-11-17
      • 2010-11-12
      • 1970-01-01
      • 2023-04-07
      • 2018-11-12
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      相关资源
      最近更新 更多