gpt4 book ai didi

javascript - 通过比较 2 个 JavaScript 数组生成表格数据

转载 作者:行者123 更新时间:2023-11-30 09:28:25 25 4
gpt4 key购买 nike

javascript 数组如下所示,

var course_ids = (1, 2, 3, 4);
var selected = (1, 3);

for (var x = 0; x < course_ids.length; x++) {
if (selected.find(checkCourse)) {
table_data += "<td>true</td>";
} else {
table_data += "<td>false</td>";
}
}

$('#exam_tbl tr:last').append(table_data);

function checkCourse(course_id) {
return course_id;
}

html 表格包含所有 course_ids 作为表格行中的 th。然后我想将 selected 加载到下一行。但如果选择的类(class)在那里,我想在 td 中显示 true,否则我想显示 false。 示例如下。

 ---------------------------------
| 1 | 2 | 3 | 4 | //th
----------------------------------
|true |false |true |false | //td
-----------------------------------

请帮我做这件事。

最佳答案

您可以使用 map()join() 来创建 html 字符串和 includes() 来检查元素是否包含在另一个数组。

var course_ids = [1, 2, 3, 4];
var selected = [1, 3];

$('<tr>').append(course_ids
.map(id => `<th>${id}</th>`)
.join(''))
.appendTo($('thead'))

$('<tr>').append(course_ids
.map(e => `<td>${selected.includes(e)}</td>`)
.join(''))
.appendTo($('tbody'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="exam_tb">
<thead></thead>
<tbody></tbody>
</table>

或者您可以使用 reduce() 方法并返回一个包含 thead 和 tbody 字符串的对象。

var course_ids = [1, 2, 3, 4];
var selected = [1, 3];

var html = course_ids
.reduce(function(r, e) {
r.thead += `<th>${e}</th>`;
r.tbody += `<td>${selected.includes(e)}</td>`;
return r;
}, {thead: '', tbody: ''});

$('<tr>').append(html.thead).appendTo($('thead'))
$('<tr>').append(html.tbody).appendTo($('tbody'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="exam_tb">
<thead></thead>
<tbody></tbody>
</table>

关于javascript - 通过比较 2 个 JavaScript 数组生成表格数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47883015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com