将数组中的各个值插入表格单元格

时间:2011-05-22 19:46:55

标签: javascript html

我在代码中使用for循环创建了一个表,并在多个数组中包含各种变量。我希望能够将数组中的值分别放入列中的每个表格单元格中。对于代码我有这个:

function tableCreate() {
 for (rownum = 1; rownum <= 7; rownum++) {
     document.write("<tr>");
     for (colnum = 1; colnum <= 7; colnum++) {  
     if (rownum == 1 + colnum == 1) {
         document.write("<td>" + id[0] + "</td>");
     }
     }
     document.write("</tr>");
 }
}

var id = new Array("1022", "1112", "1230", "554", "1355", "1600");
var title = new Array("Prof.", "Prof.", "Prof.", "Prof.", "Asst. Prof.", "Asst. Prof.");
var name = new Array("Catherine Adler", "Michael Li", "Maria Sanchez", "Robert Hope", "Wayne Li", "Kate Howard");
var position = new Array("Department Chair", "Asst. Chair", "TA Supervisor");
var er = new Array(2, 3, 1, 2, 1, 3);
var yoe = new Array(18, 12, 10, 23, 8, 5);
var cs = new Array(85000, 70000, 62000, 55000, 50000, 45000);

上面的代码都是外部JavaScript文档的一部分。我尝试使用if语句来生成我想要但失败的东西。现在我迷路了,一些帮助将不胜感激。要重新输入,我想说这个数组:var id = new Array(“1022”,“1112”,“1230”,“554”,“1355”,“1600”);

进入表格列并让该数组中的每个变量取一列该单元格。

2 个答案:

答案 0 :(得分:1)

不太清楚,但我认为你想要的是这个:

function tableCreate() {
 for (rownum = 1; rownum <= 7; rownum++) {
     document.write("<tr>");
     for (colnum = 1; colnum <= 7; colnum++) {  
       if (colnum == 1) {
         document.write("<td>" + id[(colnum-1)] + "</td>");
       }
     }
     document.write("</tr>");
 }
}

我希望这真的是你想要的:

// constants
var colCount=7;
var rowCount=7;

// input data
var id = new Array("1022", "1112", "1230", "554", "1355", "1600");
var title = new Array("Prof.", "Prof.", "Prof.", "Prof.", "Asst. Prof.", "Asst. Prof.");
var name = new Array("Catherine Adler", "Michael Li", "Maria Sanchez", "Robert Hope", "Wayne Li", "Kate Howard");
var position = new Array("Department Chair", "Asst. Chair", "TA Supervisor");
var er = new Array(2, 3, 1, 2, 1, 3);
var yoe = new Array(18, 12, 10, 23, 8, 5);
var cs = new Array(85000, 70000, 62000, 55000, 50000, 45000);

// make a special column.
var complicatedName;
for(index = 0; index < rowCount;index++)
{
   complicatedName[index] = title[index]+' '+name[index]+' - '+position[index];
}
colCount = colCount - 2

// create the column array.
var collist = [id,complicatedName,er,yoe,cs];

// make the table.
function tableCreate() {
 for (rownum = 1; rownum <= rowCount; rownum++) {
     document.write("<tr>");
     for (colnum = 1; colnum <= colCount; colnum++) {  
         document.write("<td>" + (collist[(colnum-1)])[(rownum-1)] + "</td>");
     }
     document.write("</tr>");
 }
}

答案 1 :(得分:0)

您的代码中存在语法错误。

改变这个:

if (rownum == 1 + colnum == 1) {

......对此:

if (rownum == 1 && colnum == 1) {