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

问题描述 投票:1回答:3

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加载到下一行。但如果选择的课程在那里我想在td显示真实,否则想要显示错误。样品如下。

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

请帮我这样做。

javascript jquery html
3个回答
2
投票

您可以使用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>

1
投票

course_ids变量必须包含一个数组。

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

正如你写的那样,course_ids有价值4

这叫做comma separated operator.

逗号运算符计算其每个操作数(从左到右)并返回最后一个操作数的值。

console.log((1,2,3,4))

1
投票
    var course_ids = [1, 2, 3, 4, 5];
    var selected = [1, 3, 4];
    var table_data = "";

    for (var x = 0; x < course_ids.length; x++) {
      if (selected.indexOf(course_ids[x]) != -1) {
        table_data += "<td>true</td>";
      } else {
        table_data += "<td>false</td>";
      }
    }

    console.log(table_data);

$('#exam_tbl tr:last').append(table_data);
© www.soinside.com 2019 - 2024. All rights reserved.