请问如何拿到port_type的值,用for循环方法?

求教怎么拿到方框里面的值?

https://img4.mukewang.com/5c3b277b0001d8eb02470214.jpg

for (var i = 0; i < res.data[0].lists[0].port_types.length; i++) {

    console.log(res.data[0].lists[0].port_types)

}

取不到啊

四季花海
浏览 570回答 1
1回答

Helenr

按照你提供的截图,我拼了个数据var res = {&nbsp; &nbsp; data: [&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lists: [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mac: "",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; port_types: [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { act: 1, port_type: 1 },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { act: 0, port_type: 2 },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { act: 1, port_type: 3 }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; ]}在浏览器 (Chromium) 里展开结构和你给的图是一样的res.data[0].lists[0].port_types 是一个列表,可以简单的用 forEach 遍历res.data[0].lists[0].port_types.forEach(typeObj => {&nbsp; &nbsp; console.log(typeObj);&nbsp; &nbsp; // { act: 1, port_type: 1 }&nbsp; &nbsp; // { act: 0, port_type: 2 }&nbsp; &nbsp; // { act: 1, port_type: 3 }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // 或&nbsp; &nbsp; console.log(typeObj.port_type);&nbsp; &nbsp; // 1&nbsp; &nbsp; // 2&nbsp; &nbsp; // 3});当然也可以用 for 遍历,但为了清楚明了,最好使用一个中间变量(你的代码的问题就在于输出的东西不对,不应该是 ....port_types,而应该是 ....port_types[i]):var portTypes = res.data[0].lists[0].port_types;for (let i = 0; i < portTypes.length; i++) {&nbsp; &nbsp; console.log(portTypes[i]);&nbsp; &nbsp; console.log(portTypes[i].port_type);}当然,实际上 res.data 是一个数组,其中每个元素的 list 又是一个数组,再往下的 port_types 又是一个数组,要完全遍历的话,需要三重循环for (let i = 0; i < res.data.length; i++) {&nbsp; &nbsp; const lists = res.data[i].lists;&nbsp; &nbsp; for (let j = 0; j < lists.length; j++) {&nbsp; &nbsp; &nbsp; &nbsp; const portTypes = lists[j].port_types;&nbsp; &nbsp; &nbsp; &nbsp; for (let k = 0; k < portTypes.length; k++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(portTypes[k]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(portTypes[k].port_type);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript