我可以在一个函数上访问JSON数据,但不能在另一个函数中访问

时间:2017-10-11 10:59:05

标签: javascript json

我的代码有两个函数f1和f2。 在f1中,我设置了一个jsonobject,我可以访问它。 但是在f2中它是不可能的(它将返回“未定义”)。

该代码用于存放街道的地址并在此处(摘要)

locationForm.addEventListener('submit',f2);
var JsonStreet = {"Adresses":[]};


function f2(e){
while (streetNumber < streetEnd) {
console.log(JsonStreet.Adresses[0]); //here it is undefined
    f1(e);
    streetNumber ++;
  }
}


function f1(e){
e.preventDefault();
//creation of JsonAdress
JsonStreet.Adresses.unshift(JsonAdress);
//data adding to the Json depending on streetnumber
console.log(JsonStreet.Adresses[0]); //That's works well, the json seems good
}

根据功能,有人知道为什么会有差异吗?

编辑: 在这里,我的代码更精确:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <title>MyGeoCodeApp</title>
</head>

<body>

  <div class="container"> //everything that will be display
    <h2 id="text-center"> Enter location :</h2>
    <form  id="location-form">
      <input type="text" id="location-input" class="form-control
      form-control-lg">
      <button type="submit" class="btn btn-primary btn-block">submit</button>
</form>
  <h2 id="text-center"> Last street number :</h2>
<form  id="EndOfStreet-form">
  <input type="text" id="EndOfStreet-input" class="form-control
  form-control-lg">


</form>
  <div  class="card-block" id="formatted-address"></div>
  <div  class="card-block" id ="adress-components"></div>
  <div  class="card-block" id ="geo-components"></div>
  <div  class="card-block" id="json"></div>
  </div>

<script>
//call
//geocode();
//get location formattedAdd
var locationForm = document.getElementById('location-form');
var EndOfStreetForm = document.getElementById('EndOfStreet-form');
//listen for submit
locationForm.addEventListener('submit',streetAdresses);

var JsonStreet = {"Adresses":[]};
var streetNumber = 1;
var JsonAdress= {"Adress":" ","Latitude":" ", "Longitude":" "};


function streetAdresses(e)
{
  var EndOfStreet = document.getElementById('EndOfStreet-input').value;

 e.preventDefault();
  while (streetNumber-1<EndOfStreet) {

      var location = document.getElementById('location-input').value;
      location = streetNumber + location;
      //request to google to get the data
      axios.get('https://maps.googleapis.com/maps/api/geocode/json',{
      params:{
        address:location,
        key:'PRIVATE_Key'
      }
    })
    .then(function(response){
    //Log full response
    //  console.log(response);
      //fornatted address
      var formattedAdd = (response.data.results[0].formatted_address);
      var formattedAddoUT = `
        <ul class="list-group">
          <li class="list-group-item">${formattedAdd}</li>
        </il>
      `;

    //adressComponents
  /*  var adressComponents = response.data.results[0].address_components;
    var adressComponentsOut = '<ul class="list-group">';
    for (var i = 0; i < adressComponents.length; i++) {
      adressComponentsOut +=`
    <li class="list-group-item">${adressComponents[i].types[0]} : ${adressComponents[i].long_name}</li>
      `;
    }
    adressComponentsOut += '</ul>'*/


    //geometricValues
    var lat  = response.data.results[0].geometry.location.lat;
    var lng = response.data.results[0].geometry.location.lng;
    var geoOutput=`
    <ul class="list-group">
    <li class="list-group-item">lattitude : ${lat}</li>
    <li class="list-group-item">longitude : ${lng}</li>
    </ul>`;

    //set the json
    var JsonAdress = {"Adress":" ","Latitude":" ", "Longitude":" "};
    JsonAdress.Adress=formattedAdd;
    JsonAdress.Latitude=lat;
    JsonAdress.Longitude= lng;
    //var JsonObj = JSON.stringify(JsonAdress);

    JsonStreet.Adresses.unshift(JsonAdress);
    console.log(JsonStreet.Adresses[0]);  //that's go well


    })
    .catch(function(error){
      console.log(error);
    });
    //}
    streetNumber ++;

  }
console.log(JsonStreet.Adresses[0]); //That's go "undefined"
console.log(JsonStreet); // That is well
}


</script>

</body>
</html>

最后,我附上了我得到的照片 here

2 个答案:

答案 0 :(得分:0)

  

unshift()方法将新项添加到数组的开头,并且   返回新的长度。

所以,在这一行中,您要将JsonAdress添加到JsonStreet.Adresses数组

JsonStreet.Adresses.unshift(JsonAdress);

因此这里不是空的。

console.log(JsonStreet.Adresses[0]);

此外,您在f1()内调用f2()并在调用f1()之前访问数组。因此,您的对象在此之前不会被修改,并且它是空数组。

function f2(e){
    while (streetNumber < streetEnd) {
       f1(e);// call this function before console.log()
       console.log(JsonStreet.Adresses[0]); //now it is not undefined
       streetNumber ++;
    }
}

答案 1 :(得分:0)

目前您正在打印阵列并且仅在之后填充它。

您在f2 'submit'内执行eventListener,并且您在f1内执行了f2,这意味着代码{ {1}}在f2代码之前运行,因此您的数组为空且未定义,然后在f1运行后,它会在f1

内被定义并显示

因此,要解决此问题,您只需将console.log移至console.log(JsonStreet.Adresses[0]);

以下即可