![](/img/trans.png)
[英]Undefined value is being populated when i try to access javascript array
[英]I try to access the array elements but get undefined
我无法访问数组的元素。 我没有放整个代码,因为它太长了,但我解释了我做了什么。
我有以下类型的数组结果:
results [i] = myArr.Items [i]
左右完成:
{3: {...}, 4: {...}, 9: {...}} 3: {type: 'Image', id_a: '123456', value: 'moto_guzzi_v100_mandello.jpg', number: 3, id: 3} 4: {type: 'Text', id_a: '123456', value: 'The star of the Piaggio group stand is without doubt... Discover all her secrets with our video', number: 2, id: 2} 9: {type: 'Text', id_a: '123456', value: 'The V100 Mandello celebrates the 100th anniversary of the house and… ovative. Let's find out together with our video. ', Number: 4, id: 4}
我正在尝试恢复项目,如下面的代码所示:
Object.entries(results).forEach(function (item) { let child = document.createElement("tr"); child.innerHTML = ` <td>${item.number}</td> <td>${item.type}</td> <td>${item.value}</td> table.appendChild(child); })
<table id="my-table" width="90%"> <tr> <th>Number</th> <th>Type</th> <th>Value</th> </tr> </table>
我只是得到每个值的undefined
值。
任何人都可以向我解释访问这些值的正确方法吗?
不要使用Object.entries
。 迭代数组的正确形式是:
for (const i in results) {
const item = results[i];
let child = document.createElement("tr");
child.innerHTML = `
<td>${item.number}</td>
<td>${item.type}</td>
<td>${item.value}</td>
table.appendChild(child);
}
Object.entries() 使您的 object 列表可迭代,但如果您 console.log 每个item
,您将看到它的数组包含 2 个条目 - 索引 (0) 和数据 (1)
let results = { 3: { type: 'Image', id_a: '123456', value: 'moto_guzzi_v100_mandello.jpg', number: 3, id: 3 }, 5: { type: 'Text', id_a: '123456', value: 'The star of the Piaggio group stand is without doubt... Discover all her secrets with our video', number: 2, id: 2 }, 8: { type: 'Text', id_a: '123456', value: 'The V100 Mandello celebrates the 100th anniversary of the house and… ovative. Let\'s find out together with our video. ', Number: 4, id: 4 } }; Object.entries(results).forEach(item => { item = item[1]; let child = document.createElement("tr"); child.innerHTML = ` <td>${item.number}</td> <td>${item.type}</td> <td>${item.value}</td>` document.querySelector('#my-table').appendChild(child); })
<table id="my-table" width="90%" border='1'> <tr> <th>Number</th> <th>Type</th> <th>Value</th> </tr> </table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.