简体   繁体   English

如何修复无法读取未定义的属性“纬度”

[英]How to fix Cannot read property 'Latitude' of undefined

My code does not work.我的代码不起作用。 I need to compare the value of the array to the value that was entered and return the latitude and longitude values in order to plot this point on the map, but only get the error Cannot read property Latitude of undefined.我需要将数组的值与输入的值进行比较并返回纬度和经度值,以便 plot 在 map 上的这一点,但只会得到错误无法读取未定义的属性纬度。

var auto1 = [{"Latitude": 42.389, "Longitude": -8.567, title: "test"}];

var digit = document.getElementById('searchmap');
var ret = digit.value;

function search(namek, myarray){
   for(var i=0; i<myarray.length; i++){
      if(myarray[i].title === namek){
         return myarray[i];
       } else{ return false;
       }
    }
 }

var obj = search(ret,auto1);
function showauto(){
     var retu = new google.maps.LatLng(obj.Latitude,obj.Longitude);
     map.setCenter(retu);
 }

I want map.setCenter(retu) works.我想要 map.setCenter(retu) 工作。 Thanks谢谢

Your search function has a conditional return value.您的search function 具有条件返回值。 So in the case that none of the items in the array argument match the condition, it will return undefined.因此,如果数组参数中没有任何项与条件匹配,它将返回 undefined。 You need to handle this case before trying to reference properties on the function's return value.在尝试引用函数返回值的属性之前,您需要处理这种情况。

Edit: I'm hesitant to provide a working example because I have no idea what your spec is, but here's one that would work:编辑:我不愿提供一个可行的示例,因为我不知道您的规格是什么,但这是一个可行的示例:

function showauto() {
  const obj = search(ret, auto1)
  if (obj) {
    var retu = new google.maps.LatLng(obj.Latitude,obj.Longitude)
    map.setCenter(retu)
  }
}

In the case that search returns a falsy value, the showauto function will not attempt to run the maps logic.search返回虚假值的情况下, showauto function 将不会尝试运行映射逻辑。

Try something like this:尝试这样的事情:

function search(name, myarray) {
    const foundItem = myarray.find(element => {
        return element.title === name
    })
    return foundItem
}

Also I'm not quite sure what are you doing, but maybe you have error in that ret variable另外我不太确定你在做什么,但也许你在那个 ret 变量中有错误

var ret = digit.value

You are not providing correct value to the function search on line: var obj = search(ret,auto1) so your search function fails to find anything and it returns no value, and obj becomes undefined and you can't access property of undefined because there is none.您没有为 function 在线搜索提供正确的值: var obj = search(ret,auto1)所以您的搜索 function 找不到任何东西并且它没有返回任何值,并且obj变为undefined并且您无法访问undefined的属性,因为空无一人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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