简体   繁体   中英

Pass variables between functions in Javascript?

I have functions that perform distance calculation with Google Maps.

They work smoothly, returning me the requested values.

This function returns a first value

  function calcDistance(response) {

    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;


    for (var i = 0; i < origins.length; i++) {
     var results = response.rows[i].elements;

     for (var j = 0; j < results.length; j++) {
   
    distanzafissa = results[j].distance.value;
    distanzafissa = distanzafissa / 1000;
    
    distanzafissarr = Math.round(distanzafissa*100)/100;
    }
   }
  }

I would like the value of distanzafissarr to pass to another function so coded:

    function computeTotalDistance(result) {
      var total = 0;
      var myroute = result.routes[0];
      for (i = 0; i < myroute.legs.length; i++) {
        total += myroute.legs[i].distance.value;
      }
      total = total / 1000;
      
      
    var totalarr = Math.round(total*100)/100;
   }

I have tried to follow various answers on this site, but always getting errors.

You are not returning any value from a function so it returns undefined . Put return at the end of the function:

 function computeTotalDistance(result) {
      var total = result + 1;
      return total; // missing
   }

You need to make your funcions a getter or return functions like the following example.

function getCalculatedDistance(response) {

    let origins = response.originAddresses;
    let destinations = response.destinationAddresses;
    let distanzaFissarr;

    for (let i = 0; i < origins.length; i++) {
        let results = response.rows[i].elements;

        for (let j = 0; j < results.length; j++) {

            let distanzaFissa = (results[j].distance.value) / 1000;
            distanzaFissarr = Math.round(distanzaFissa * 100) / 100;
        }
    }

    return distanzaFissarr; // Return data
}


function getTotalDistance(result) {

    let total = 0;
    let myroute = result.routes[0];

    for (let i = 0; i < myroute.legs.length; i++) {
        total += myroute.legs[i].distance.value;
    }

    total = total / 1000;

    return Math.round(total * 100) / 100; // Return data
}

If you don't do that you function will return undefined so you will not get access to any of the function variables.

Check JavaScript Scope to determines the accessibility (visibility) of variables.

In order to use the returned data, you can do something like that

const calculatedDistance = getCalculatedDistance(response);
const totalDistance = getTotalDistance(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM