我通過獲取 api 獲取資料。這是從 API 獲取資料后,我得到的資料是這樣的:
const info={
"suggesstion":0,
"idea":{
"prod": [
{
"group": {
"subj": "English",
"class": "one",
"section": "1A"
},
},
{
"group": {
"subj": "Physics",
"class": "nine",
"section": "2A"
},
},
{
"group": {
"subj": "Math",
"class": "Ten",
"section": "3A"
},
}
]
}
}
現在,當我嘗試呼叫 html 表中的資料時,我正在使用一個函式,以便我可以一起呼叫表中的值。這是我的功能。
const tableD= info?.idea?.prod.map((info) => {
const nS= [],
nC= [],
nSec= [];
nS.push(info.group.subj)
nC.push(info.group.class)
nSec.push(info.group.section)
let table= []
for (let a in nS) {
for (let b in nC) {
for (let c in nSec) {
const nSAll= nS[a],
nCAll= nC[b],
nSecAll= nSec[c];
table =
`<td>${nSAll}</td>
<td>${nCAll}</td>
<td>${nSecAll}</td>
</tr>`
}
}
}
return table;
}).join(' ');
console.log(tableD);
現在,當我嘗試在 html 中使用它時,我得到了這張表:

但我想為列中的每一行添加序列號,在這里將是 1 ,2 ,3

這是我的 html:
<table class="demo">
<thead>
<tr>
<th>No</th>
<th>Subj</th>
<th>Class</th>
<th>Section</th>
</tr>
</thead>
<tbody>
<tr>
<td>${htmlDatasheet}</td>
</tr>
</tbody>
</table>
我怎么能在功能中做到這一點,任何人都可以幫助我嗎?感謝您提前嘗試!
uj5u.com熱心網友回復:
您可以維護一個變數并在每次迭代中使用增量值
....
let counter = 1; //declare here
const tableD= info.idea.prod.map((info) => {
....
table =
`<td>${counter }</td> //use here
<td>${nSAll}</td>
<td>${nCAll}</td>
<td>${nSecAll}</td>
</tr>`
....
uj5u.com熱心網友回復:
在地圖函式上使用索引變數來獲取索引值。
const tableD = info?.idea?.prod.map((info, index) => {
const nS = [],
nC = [],
nSec = [];
nS.push(info.group.subj)
nC.push(info.group.class)
nSec.push(info.group.section)
let table = []
for (let a in nS) {
for (let b in nC) {
for (let c in nSec) {
const nSAll = nS[a],
nCAll = nC[b],
nSecAll = nSec[c];
table =
`<tr>
<td>${index 1}</td>
<td>${nSAll}</td>
<td>${nCAll}</td>
<td>${nSecAll}</td>
</tr>`
}
}
}
return table;
}).join(' ');
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/535548.html
