代码之家  ›  专栏  ›  技术社区  ›  user955857

在JS中使用分隔符从一个列数组创建两个列数组

  •  0
  • user955857  · 技术社区  · 8 年前

    我有一个包含纬度和经度的JavaScript数组。现在,我的数组是这样的格式,并且是array类型:

    [Lat,Lon]
    
    [Lat,Lon]
    
    [Lat,Lon]
    

    [Lat][Lon]
    
    [Lat][Lon]
    
    [Lat][Lon]
    

    我如何在JS中做到这一点?我的最佳猜测是使用单列数组中的逗号作为分隔符,但我不确定如何实现这一点。我对使用JQuery持开放态度。

    var getOutline = 'lat1,lon1/lat2,lon2/lat3,lon3'; //Sample
    var temporaryArray = new Array();
    temporaryArray = getOutline.split("/");
    console.log(temporaryArray)
    
    var temporaryArray2 = new Array();
    temporaryArray2 = temp.split(",");
    console.log(temporaryArray2)
    

    但是,我的第二个函数不起作用,因为split函数不分割数组类型。

    2 回复  |  直到 8 年前
        1
  •  1
  •   FieryCat    8 年前

    如果需要,试试下一个 {lat1: {lon1: value, lon2: ...}, ...}

    var getOutline = 'lat1,lon1/lat2,lon2/lat3,lon3',
        result = {};
    
    getOutline.split('/').forEach(function (coord) {
        var tmp = coord.split(',');
        result[tmp[0]][tmp[1]] = '{something that is needed as a value}';
    });
    

    或者,如果需要的话 [[lat1, lon1], [lat2, lon2], ...] :

    var getOutline = 'lat1,lon1/lat2,lon2/lat3,lon3',
        result = [];
    
    getOutline.split('/').forEach(function (coord) {
        result.push(coord.split(',').map(Number));
    });
    
        2
  •  1
  •   JuhG    8 年前

    var array = [
      '1,2',
      '3,4',
    ];
    
    var newArray = array.map(function(i) {
      return i.split(',');
    });
    
    // Returns an array of arrays
    // [ [1, 2], [3, 4] ]
    
    推荐文章