亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從對象數組生成 HTML 表格

從對象數組生成 HTML 表格

www說 2023-12-04 17:03:05
我一直在嘗試生成一個函數來從對象數組創建 HTML 表。這是需要做成表的數組。let units = [    {        'code': 'COMP2110',        'title': 'Web Technology',         'offering': 'S1'    },      {        'code': 'COMP2010',        'title': 'Algorithms and Data Structures',         'offering': 'S1'    },    {        'code': 'COMP2150',        'title': 'Game Design',         'offering': 'S1'    },    {        'code': 'COMP2320',        'title': 'Offensive Security',         'offering': 'S1'    },    {        'code': 'COMP2200',        'title': 'Data Science',         'offering': 'S2'    },    {        'code': 'COMP2250',        'title': 'Data Communications',         'offering': 'S2'    },    {        'code': 'COMP2300',        'title': 'Applied Cryptography',         'offering': 'S2'    },    {        'code': 'COMP2000',        'title': 'Object-Oriented Programming Practices',         'offering': 'S2'    },    {        'code': 'COMP2050',        'title': 'Software Engineering',         'offering': 'S2'    },    {        'code': 'COMP2100',        'title': 'Systems Programming',         'offering': 'S2'    }]我嘗試過一個功能,但我不知道如何讓它工作。我也不知道如何查詢該函數。function unit_table() {    var totalRows = 3;    var cellsInRow = 3;    function drawTable() {        // get the reference for the body        var first = document.getElementById('first');        // creates a <table> element        var tbl = document.createElement("table");        // creating rows        for (var r = 0; r < totalRows; r++) {            var row = document.createElement("tr");            // create cells in row            for (var c = 0; c < cellsInRow; c++) {                m=0;                var cell = document.createElement("td");                var cellText = document.createTextNode(units[n][m]);                cell.appendChild(cellText);                row.appendChild(cell);                m=m+1;            }           任何幫助將不勝感激。
查看完整描述

4 回答

?
紅顏莎娜

TA貢獻1842條經驗 獲得超13個贊

如果是包含對象鍵的字符串,則它將units[n][m]起作用。m


example units[0]["code"]將返回第一個對象的代碼值。


填充表可以通過在字符串中動態生成 html 并將table.innerHTML其設置為表來完成。


為此,我們使用以下方法迭代鍵for (let key in object)


對于列名稱


let tableString="<tr>"

for(let column in units[0]){

  tableString+=`<th>${column}</th>`

}

上面的代碼將生成一個像這樣的字符串


<tr>

<th>code</th>

<th>title</th>

<th>offering</th>

</tr>

對于列數據


tableString+="</tr>"

units.forEach(element => {

    tableString+="<tr>"

    for(let prop in element){

      tableString+=`<td>${element[prop]}</td>`

    }

    tableString+="</tr>"

});

上面將生成這樣的字符串,并且這將重復直到數組末尾


 <tr>

   <td>COMP2110</td>

   <td>Web Technology</td>

   <td>S1</td>

   </tr>

  <tr>...

  </tr>

  <tr>...

  </tr>

最后


 document.querySelector('#tb').innerHTML=tableString;

let units = [

    {

        'code': 'COMP2110',

        'title': 'Web Technology', 

        'offering': 'S1'

    },  

    {

        'code': 'COMP2010',

        'title': 'Algorithms and Data Structures', 

        'offering': 'S1'

    },

    {

        'code': 'COMP2150',

        'title': 'Game Design', 

        'offering': 'S1'

    },

    {

        'code': 'COMP2320',

        'title': 'Offensive Security', 

        'offering': 'S1'

    },

    {

        'code': 'COMP2200',

        'title': 'Data Science', 

        'offering': 'S2'

    },

    {

        'code': 'COMP2250',

        'title': 'Data Communications', 

        'offering': 'S2'

    },

    {

        'code': 'COMP2300',

        'title': 'Applied Cryptography', 

        'offering': 'S2'

    },

    {

        'code': 'COMP2000',

        'title': 'Object-Oriented Programming Practices', 

        'offering': 'S2'

    },

    {

        'code': 'COMP2050',

        'title': 'Software Engineering', 

        'offering': 'S2'

    },

    {

        'code': 'COMP2100',

        'title': 'Systems Programming', 

        'offering': 'S2'

    }

]

let tableString="<tr>"

for(let column in units[0]){

  tableString+=`<th>${column}</th>`

}

tableString+="</tr>"

units.forEach(element => {

    tableString+="<tr>"

    for(let prop in element){

      tableString+=`<td>${element[prop]}</td>`

    }

    tableString+="</tr>"

});

document.querySelector('#tb').innerHTML=tableString;

table td {

border:1px solid black;

}

<table id="tb">


</table>


查看完整回答
反對 回復 2023-12-04
?
暮色呼如

TA貢獻1853條經驗 獲得超9個贊

您的代碼基本上是正確的,但存在一些結構問題。您在函數內部定義函數會導致一些問題,您沒有聲明所有變量并且無法正確訪問單元??匆幌?,如果您需要更多幫助,請告訴我。


let units = [

    {

        'code': 'COMP2110',

        'title': 'Web Technology', 

        'offering': 'S1'

    },  

    {

        'code': 'COMP2010',

        'title': 'Algorithms and Data Structures', 

        'offering': 'S1'

    },

    {

        'code': 'COMP2150',

        'title': 'Game Design', 

        'offering': 'S1'

    },

    {

        'code': 'COMP2320',

        'title': 'Offensive Security', 

        'offering': 'S1'

    },

    {

        'code': 'COMP2200',

        'title': 'Data Science', 

        'offering': 'S2'

    },

    {

        'code': 'COMP2250',

        'title': 'Data Communications', 

        'offering': 'S2'

    },

    {

        'code': 'COMP2300',

        'title': 'Applied Cryptography', 

        'offering': 'S2'

    },

    {

        'code': 'COMP2000',

        'title': 'Object-Oriented Programming Practices', 

        'offering': 'S2'

    },

    {

        'code': 'COMP2050',

        'title': 'Software Engineering', 

        'offering': 'S2'

    },

    {

        'code': 'COMP2100',

        'title': 'Systems Programming', 

        'offering': 'S2'

    }

]


key=['code','title','offering'];


console.log(units[1].title);


    var totalRows = 3;

var cellsInRow = 3;

var n=0,m=0;


    function drawTable() {

    console.log('draw');

        // get the reference for the body

        var first = document.getElementById('first');


        // creates a <table> element

        var tbl = document.createElement("table");


        // creating rows

        for (var r = 0; r < totalRows; r++) {

            var row = document.createElement("tr");


         // create cells in row

             m=0;

             for (var c = 0; c < cellsInRow; c++) {

               

                var cell = document.createElement("td");

                var cellText = document.createTextNode(units[n][key[m]]);

                cell.appendChild(cellText);

                row.appendChild(cell);

                m=m+1;

            }           


            n=n+1;

            console.log(row);

    tbl.appendChild(row); // add the row to the end of the table body

        }


     first.appendChild(tbl); // appends <table> into <first>

}


    // your code here



window.onload=drawTable(); 

<div id='first'></div>


查看完整回答
反對 回復 2023-12-04
?
慕妹3146593

TA貢獻1820條經驗 獲得超9個贊

您可以通過利用DOM API和Array.prototype.reduce方法輕松實現這一點 - 例如:

const units = [{

? ? 'code': 'COMP2110',

? ? 'title': 'Web Technology',

? ? 'offering': 'S1'

? },

? {

? ? 'code': 'COMP2010',

? ? 'title': 'Algorithms and Data Structures',

? ? 'offering': 'S1'

? },

? {

? ? 'code': 'COMP2150',

? ? 'title': 'Game Design',

? ? 'offering': 'S1'

? },

? {

? ? 'code': 'COMP2320',

? ? 'title': 'Offensive Security',

? ? 'offering': 'S1'

? },

? {

? ? 'code': 'COMP2200',

? ? 'title': 'Data Science',

? ? 'offering': 'S2'

? },

? {

? ? 'code': 'COMP2250',

? ? 'title': 'Data Communications',

? ? 'offering': 'S2'

? },

? {

? ? 'code': 'COMP2300',

? ? 'title': 'Applied Cryptography',

? ? 'offering': 'S2'

? },

? {

? ? 'code': 'COMP2000',

? ? 'title': 'Object-Oriented Programming Practices',

? ? 'offering': 'S2'

? },

? {

? ? 'code': 'COMP2050',

? ? 'title': 'Software Engineering',

? ? 'offering': 'S2'

? },

? {

? ? 'code': 'COMP2100',

? ? 'title': 'Systems Programming',

? ? 'offering': 'S2'

? }

];


const createEmptyTable = () => {

? const tableEl = document.createElement('table');


? tableEl.appendChild(document.createElement('thead'));

? tableEl.appendChild(document.createElement('tbody'));


? return tableEl;

};


const createTableHeadersRow = data => {

? const fields = Object.keys(data);


? return fields.reduce((trEl, fieldName) => {

? ? const tdEl = document.createElement('th');


? ? tdEl.appendChild(document.createTextNode(fieldName));

? ? trEl.appendChild(tdEl);


? ? return trEl;

? }, document.createElement('tr'));

};


const createTableBodyRow = data => {

? const values = Object.values(data);


? return values.reduce((trEl, value) => {

? ? const tdEl = document.createElement('td');


? ? tdEl.appendChild(document.createTextNode(value));

? ? trEl.appendChild(tdEl);


? ? return trEl;

? }, document.createElement('tr'));

};


const createUnitTable = unitsArray => {

? return unitsArray.reduce((tableEl, unit, idx) => {

? ? const tableNeedsHeaderRow = idx === 0;


? ? if (tableNeedsHeaderRow) {

? ? ? tableEl.querySelector('thead').appendChild(createTableHeadersRow(unit));

? ? }


? ? tableEl.querySelector('tbody').appendChild(createTableBodyRow(unit));


? ? return tableEl;

? }, createEmptyTable());

};


document.querySelector('div').appendChild(createUnitTable(units));

td {

? padding: .5rem;

? border: 1px solid black;

}


th {

? text-transform: capitalize

}

<div></div>



查看完整回答
反對 回復 2023-12-04
?
至尊寶的傳說

TA貢獻1789條經驗 獲得超10個贊

對象數組示例


let cars = [

      {

        "color": "purple",

        "type": "minivan",

        "registration": new Date('2017-01-03'),

        "capacity": 7

      },

      {

        "color": "red",

        "type": "station wagon",

        "registration": new Date('2018-03-03'),

        "capacity": 5

      }]

功能 :


function ArrayToHtmlTable(htmlelement,ArrayObject) {

  TableHeader = Object.keys(ArrayObject[0])

    .map((x) => "<th>" + x + "</th>")

    .join("");


  TableBody = ArrayObject.map(

    (x) =>

      "<tr>" +

      Object.values(x)

        .map((x) => "<td>" + x + "</td>")

        .join() +

      "<tr>"

  ).join("");


  document.getElementById(

    htmlelement

  ).innerHTML += `<table> ${TableHeader} ${TableBody}</table>`;

}

函數調用:


ArrayToHtmlTable("testTable",cars) 


查看完整回答
反對 回復 2023-12-04
  • 4 回答
  • 0 關注
  • 201 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號