此代码查找javascript对象中“ AL”的位置,然后搜索“ AL”的位置以查找与“ AL”相关的其他属性,例如宽度。
为什么此代码返回对象中最后一项的宽度,而不是“ AL”的宽度?
我可以成功编码位置[0]
,但我希望将位置编码为变量[z]
myObj = {
"type":"A",
"info": [
{ "item":"1", "properties":{ "id":"AL", "height": "25", width: "50" } },
{ "item":"2", "properties":{ "id":"PO", "height": "30", width: "40" } },
{ "item":"3", "properties":{ "id":"RA", "height": "20", width: "100" } }
]
}
myObj.info.forEach(function(e, z) {
if (e.properties.id == "AL") document.getElementById("position").innerHTML = z;
document.getElementById("width").innerHTML = myObj.info[z].properties.width;
});
<p>Position in object:<span id="position"></span></p>
<p>Width:<span id="width"></span></p>
答案 0 :(得分:0)
使用代码块更改if语句,以便最后一条语句将在if语句内执行
myObj = {
"type":"A",
"info": [
{ "item":"1", "properties":{ "id":"AL", "height": "25", width: "50" } },
{ "item":"2", "properties":{ "id":"PO", "height": "30", width: "40" } },
{ "item":"3", "properties":{ "id":"RA", "height": "20", width: "100" } }
]
}
myObj.info.forEach(function(e, z) {
if (e.properties.id == "AL") {
document.getElementById("position").innerHTML = z;
document.getElementById("width").innerHTML = myObj.info[z].properties.width;
}
});
<p>Position in object:<span id="position"></span></p>
<p>Width:<span id="width"></span></p>