按对分组时将数组转换为字符串

Convert array to string while grouping by pairs

我在 javascript 中有一个纬度和经度数组,如下所示:

a = [lat1, lon1, lat2, lon2, lat3, lon3, ...] // assert(a.length % 2 = 0)

我想创建一个这样的字符串:

s = "lat1,lon1 lat2,lon2 lat3,lon3 ..."

也就是说,每个 latlon 对都有一个逗号分隔,并且这些对由 space 分隔。

我有点卡在这里(主要是因为我对javascript知之甚少):

    function polylineToKml(p)     
    {
        var s = "";
        for (var i = 0; i < p.length; i+=2)
        {
            var lat = p[i];
            var lon = p[i+1]
            // now what?
        }
    }
function polylineToKml(p) {
    var s = "";
    for (var i = 0, l = p.length; i < l; i += 2) {
        var lat = p[i];
        var lon = p[i + 1];
        s += lat + ',' + lon;

        // don't add a space at the end
        if (i !== l - 2) s += ' ';
    }
    return s;
}

DEMO

一种方式:

var s = [];
for (var i = 0; i < a.length; i+=2)
{
    s.push(a[i] + "," + a[i+1]);
}

s = s.join(" ");

另一种方式...

function polylineToKml(p){
    var s = "";
    for (var i = 0; i < p.length - 1; i++){
        s += p[i] + ",";
    }
    s += p[p.length - 1];
    return s;
}

以更实用的方式:

function polylineToKml(p) {
  return p.map(function(el, i) {
    return el + (i % 2 > 0 ? " " : ",");
  }).join("").trim();
}

如果您的环境支持 ES6:

var polylineToKml = p =>
  p.map((el, i) => el + (i % 2 > 0 ? " " : ",")).join("").trim();

您应该采用适当的方式来组织您的数据集,一种方法是使用 JSON 数组和键值对,例如

<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var a = [1.234, 2.345, 3.456, 5.456, 4.653, 2.567]
var coordinates = [];
for (var i=0; i < a.length; i=i+2){
    coordinates[i/2] = {"latitude":a[i], "longitude":a[i+1]}
}

for (var i=0; i < coordinates.length; i++){
    document.getElementById("demo").innerHTML +=
    coordinates[i].latitude + ", " + coordinates[i].longitude + "<br>";
}
</script>
</body>
</html>

这样,坐标将表示为:

coordinates = [
    {"latitude":"1.234", "longitude":"2.345"}, 
    {"latitude":"3.456", "longitude":"5.456"},
    {"latitude":"4.653", "longitude":"2.567"}
];

http://www.w3schools.com/json/default.asp

上了解更多信息