Reputation: 267
Here I have two functions: updateTooltipContent
and distance
.
When I try to call distance(latt)
in updateTooltipContent
it does not return any value. I cannot see why not
CODE:
function updateTooltipContent() {
var fullt = $(this).width();
var startt = $(this).position().left + 200;
var endt = fullt + startt;
var latt = $(this).attr("lat");
return "Spending: " + formatTime(fullt) +
"</br> Between:(" + formatTime(startt) + " and " +
formatTime(endt) + ") </br>" + distance(latt) + "km";
}
});
function distance(latt) {
var bigArray = nArray();
var dis = 0.00;
for (var x = 0; x < bigArray.length; x++) {
if (bigArray[x].lat == latt) {
dis = bigArray[x].DISTANCE_FROM_PREVIOUS_OBJECT_LOCATION;
break; // no point doing anymore loops as we've found the answer
}
return dis;
}
}
This code work great but when I try to put some of code in function then wont to work: WORKING CODE WITHOUT FUNCTION DISTANCE()
function updateTooltipContent() {
var fullt = $(this).width();
var startt = $( this ).position().left + 200;
var endt = fullt + startt;
var latt = $(this).attr("lat");
var bigArray = nArray();
var distance = 0.00;
for(var x = 0; x < bigArray.length; x++)
{
if(bigArray[x].lat == latt)
{
distance = bigArray[x].DISTANCE_FROM_PREVIOUS_OBJECT_LOCATION;
break; // no point doing anymore loops as we've found the answer
}
}
return "Spending: "+formatTime(fullt) + "</br> Between:("+formatTime(startt) + " and " +formatTime(endt)+") </br>" + distance.toFixed(2) + "km";
}
});
Upvotes: -1
Views: 118
Reputation: 26
Once bigArray[x].lat == latt, statement break will be invoked, your for loop will be skipped immediately; since your return statement stays in the loop, of course nothing will return.
To fix this issue, just move your return statement out of the for loop.
Upvotes: 1