首页 > 解决方案 > Javascript 获取子数组的第二个元素(用逗号分隔)

问题描述

我的控制器有一个输出数组,如下所示:

[
  ["48.85585695936588,2.317734961729684"],
  ["48.87234429654349,2.351466422300973"],
  ["48.85376742273335,2.3639977028185513"]
]

我想从这个坐标创建一个多边形,所以这个数据结构(数组):

数组位置

这是我的代码:

for(var j = 0; j < output.length; j++) {
    var points = [];
    var quart = JSON.parse(output[j]['polygon']);
    for (var i = 0; i < quart.length; i = i+2) {
        points.push({
           lat: parseFloat(quart[i]),
           lng: parseFloat(quart[i+1])
       });
 }

我无法获得经度的值(逗号后的那个)......

谢谢你。

标签: javascriptarrays

解决方案


一种方法如下:

// original array:
let twoDimensionalArray = [
    ["48.85585695936588,2.317734961729684"],
    ["48.87234429654349,2.351466422300973"],
    ["48.85376742273335,2.3639977028185513"]
  ],
// using Array.prototype.map() to iterate over the
// Array, returning a new Array (assigned to the
// variable):
  coordsArray = twoDimensionalArray.map(

    // using an Arrow function to pass the current
    // Array into the function:
    (coords) => {

      // here we use destructuring to assign
      // values to a and b; to do this we take the last
      // (and only) entry of of the coords Array, and
      // split on the comma character. The first element
      // of the Array created by String.prototype.split(),
      // we then use Array.prototype.map() - along with
      // another Arrow function to iterate over the returned
      // Array to convert the Strings to numbers, with
      // parseFloat():
      [a, b] = coords.pop().split(',').map((xy)=>parseFloat(xy))

      // here we return an Object with named 'lat' and 'lng'
      // properties, assigning the relevant values to each:
      return {
        'lat': a,
        'lng': b
      }
    });

console.log(coordsArray);

参考:


推荐阅读