繁体   English   中英

尝试访问 javascript 中的 object 属性时出现“未定义”

[英]Getting "undefined" when trying to access an object property in javascript

我正在创建一个 leaflet map 来显示 map 上的代理商,并为每个代理商动态创建标记。 还有一个机构列表,当点击每个机构时,map 会自动缩放该机构的特定标记。 现在我打算在每个标记的弹出窗口中显示一些代理信息,但只有在单击代理卡或标记本身时才会显示此弹出窗口。 我在后者中取得了成功,并且在单击标记时会显示弹出窗口。 但是我在尝试通过单击代理卡来实现此目的时遇到了问题。 因此,为了澄清问题,我选择的路径如下:

首先,我的 html 卡片代码:

 <div class="card border border-secondary rounded" onclick="moveMap({{ agency.latitude }}, {{ agency.longitude }}, {{ agency.id }})" style="cursor: pointer; z-index: 1000">
... // rest of the html code

由于我的后端在 django 上,所以我使用{{}} s。

moveMap() function 中,我发送agency.latitudeagency.longitudeagency.id ,我的 javascript 代码如下:

function moveMap(lat, long, id) {
    map.flyTo([lat, long], 14, {
      animate: true,
      duration: 3.5,
    });
    openPopupByID(id);
}

在这里,将 map 移动到正确的标记后,我调用openPopupById() function,它将id作为参数, openPopupById() function 如下所示:

function openPopupByID (agency_id) {
    for (let item in markerList) {
        if (item["id"] === agency_id) {
            item.openPopup();
        }
    }
}

在这个 function 中,我使用的是如下创建的markerList

let markerList = [];

// creating markers using the coorList
for (let dataSet of coorList) {
     let latNumber = parseFloat(dataSet[0]);
     let longNumber = parseFloat(dataSet[1]);
     let marker = L.marker(L.latLng(latNumber, longNumber)).addTo(map);

     // listing agency info inside popups
     marker.bindPopup(setMarkerInfo(dataSet[2]));

     //adding each marker to the markerList
     marker["id"] = dataSet[2];
     markerList.push(marker);
}

coorList是 arrays 的列表,具有三个值agency.latitudeagency.longitudeagency.id ,索引分别为 0、1 和 2。

所以我有一个markerList ,它是标记对象的列表,并且带有marker["id"] = dataSet[2]; 我已将id属性添加到marker object。但是在openPopupByID() function 中,当我尝试访问标记的id时,我从 js 控制台收到undefined的消息。 当我尝试使用console.log(markerList)查看markerList的结构时,我得到以下信息: 在此处输入图像描述

其中我们可以清楚的看到id属性。

那么,我的问题是什么? 我做错什么了?

您必须对数组使用for of循环而不是用于对象的for in循环。

for in循环将检查 id 是否存在于 markerList 而不是列表中的每个元素

来源 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

 function openPopupByID (agency_id) { for (let item of markerList) { if (item["id"] === agency_id) { item.openPopup(); } } }

你不应该使用 for..of 而不是 for..in

function openPopupByID (agency_id) {
    for (let item of markerList) {
        console.log('test -- ', item.id, item);
        if (item["id"] === agency_id) {
            item.openPopup();
        }
    }
}

暂无
暂无

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

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