如何在表单元素的值中从数组中获得数组元素


How can I get an array element out of an array in the value of a form element?

我有一个html表单元素,它的值设置为一个数组。我想通过jQuery从数组中获取其中一个值。这是如何做到的呢?这是我的代码。如果我的解释不清楚,也许它能说明问题。谢谢你!

    var lat = 0;
    var long = 0;
    //gets the latitude and longitude when a user clicks on any place on the map
    map.on('click', function(e) {
        lat = e.latlng.lat;
        long = e.latlng.lng;
    //store the lat and long in an array
        var latlong = [lat, long];
    //here I am setting the value of my an element in my form as the array of lat and long
        document.getElement(".<?= $this->getName() ?>").set("value", latlong);
        var getLatlong = jQuery(".<?= $this->getName() ?>").val();
        console.log("retrieved: " + getLatlong);
    //it saves and retrieves properly.
    //THE PROBLEM IS HERE
    //THE PROBLEM IS HERE
      var lat = $(".<?= $this->getName() ?>").val()[0];
      var long = $(".<?= $this->getName() ?>").val()[1];
    //THE PROBLEM IS HERE
    //THE PROBLEM IS HERE

    });

这一切运行良好,但我没有得到我想要的结果。如果我尝试使用

下面的任何一行代码
    //THE PROBLEM IS HERE
      var lat = $(".<?= $this->getName() ?>").val()[0];    //returns 9
      var long = $(".<?= $this->getName() ?>").val()[1];   //returns 4
      var long = $(".<?= $this->getName() ?>").val()[3];   //returns 2
      var long = $(".<?= $this->getName() ?>").val()[4];   //returns 3
    //THE PROBLEM IS HERE

获取经度或纬度"ie: 94.2323, 12.9932"

The index [0] returns 9,
the index [1] returns 4,
the index [3] returns 2

就好像94.2323是数组,而不是像数组一样长。我希望[0]返回94.2323,[1]返回12.9932。

我尽我所能地解释这个问题并格式化这个问题。谢谢你。

您可以使用JSON.stringify()Array转换为JSON格式

document.getElement(".<?= $this->getName() ?>")
.set("value", JSON.stringify(latlong));

JSON.parse()JSON格式化的String转换为Array

var getLatlong = JSON.parse(jQuery(".<?= $this->getName() ?>").val());
console.log(getLatlong[0], getLatlong[1]); // do stuff