Javascript 为什么可以';我不能在嵌套函数中访问变量吗?
因此,我一直在使用地理位置来查找用户位置,然后查找到它的距离和一个csv位置列表。我想保存到json对象的距离,但无法在嵌套函数中访问它Javascript 为什么可以';我不能在嵌套函数中访问变量吗?,javascript,Javascript,因此,我一直在使用地理位置来查找用户位置,然后查找到它的距离和一个csv位置列表。我想保存到json对象的距离,但无法在嵌套函数中访问它 function onLocationFound(e) { console.log(e); L.marker([e.latitude, e.longitude], {icon: home_marker}).bindPopup("You are here!").addTo(m); console.log(typeof(
function onLocationFound(e) {
console.log(e);
L.marker([e.latitude, e.longitude], {icon: home_marker}).bindPopup("You are here!").addTo(m);
console.log(typeof(e.latitude));
console.log(typeof(e.longitude));
$.get('vac_sites.csv', function (csvString) {
var data = Papa.parse(csvString, { header: true, dynamicTyping: true }).data;
console.log(data)
for (let i = 0; i < data.length; i++) {
//get distance and then use dynamic variable names, make them into js objects, then store in dic with distance
var row = data[i];
console.log(row)
var myRoute = L.Routing.osrmv1({
serviceUrl: 'https://xxx.xxx.xxx:443/route/v1'
});
var self_loc = new L.Routing.Waypoint;
self_loc.latLng = L.latLng([e.latitude, e.longitude]);
var site_loc = new L.Routing.Waypoint;
site_loc.latLng = L.latLng([row.Latitude, row.Longitude]);
myRoute.route([self_loc, site_loc], function(err, routes) {
distance = routes[0].summary.totalDistance;
console.log('routing distance: ' + distance);
row.distance = distance
console.log(row)
});
通过聊天,我们解决了问题 它被缩小到改变
var行代码>到让行
听起来好像行
不知何故泄漏到了您的函数中。您应该阅读以了解两个变量声明关键字之间的差异。
简言之,var绑定到即时函数体,let绑定到即时关闭块。这可能是导致它的原因。否则,我不知道
最好使用let
,因为var
几乎总是不必要的,并且会导致问题。您是说console.log(row)
没有记录预期的值吗?是什么让您认为您无法访问该变量?您的描述不清楚,但您可能正在运行.console.log(row)显示的json对象的名称为:null distance:xxxx,而不是我的原始行json对象的名称为facility Name、lat、lon等。您不清楚“原始行对象”是什么意思。我想你的意思是“在for(vari in data)
循环的第一次迭代期间行的值。”答案是“提升”。查看链接的答案。我在那里尝试了修复,但仍然遇到相同的问题。
...
{Name: "Cate Pharmacy", Address: "500 N Missouri Ave, Corning, Arkansas", Telephone: "(870) 857-6766", Website: "<a href="https://www.catepharmacy.com/" target="_b…ow noopener noreferrer">www.catepharmacy.com/</a>", Latitude: 36.4155144, …}
...
...
{Name: "Cate Pharmacy", Address: "500 N Missouri Ave, Corning, Arkansas", Telephone: "(870) 857-6766", Website: "<a href="https://www.catepharmacy.com/" target="_b…ow noopener noreferrer">www.catepharmacy.com/</a>", Latitude: 36.4155144, distance: xxxxxx, …}
...
{Name: null, distance: 265184.8}