Javascript是否从数组向表中添加行标题?
我有一个填充表格的2d数组。有没有办法把一列一直插到左边Javascript是否从数组向表中添加行标题?,javascript,datatables,header,row,Javascript,Datatables,Header,Row,我有一个填充表格的2d数组。有没有办法把一列一直插到左边 //function to create the table function createTable(tableData) { var table = document.createElement('table'); var row = {}; var cell = {}; tableData.forEach(function (rowData) { row = table.insertRow(-1);
//function to create the table
function createTable(tableData) {
var table = document.createElement('table');
var row = {};
var cell = {};
tableData.forEach(function (rowData) {
row = table.insertRow(-1);
rowData.forEach(function (cellData) {
cell = row.insertCell();
cell.textContent = cellData;
let cellVal = cellData;
//make cells different shades of green and red for pos/neg (based on %)
if (cellVal > 0) {
cell.style.backgroundColor = '#00e100';
} else if (cellVal < 0) {
cell.style.backgroundColor = 'red';
}
});
});
document.body.appendChild(table);
}
createTable(transpose_array);
//用于创建表的函数
函数createTable(tableData){
var table=document.createElement('table');
var行={};
var-cell={};
tableData.forEach(函数(rowData){
行=table.insertRow(-1);
rowData.forEach(函数(cellData){
cell=row.insertCell();
cell.textContent=cellData;
设cellVal=cellData;
//为pos/neg设置不同深浅的绿色和红色单元格(基于%)
如果(cellVal>0){
cell.style.backgroundColor='#00e100';
}else if(cellVal<0){
cell.style.backgroundColor='红色';
}
});
});
document.body.appendChild(表);
}
createTable(转置数组);
由于颜色条件的原因,我不想向表中添加值,我只想使用数组中的值向表y轴上的每一行添加标题
图片如下:
调用forEach()
将获得第二个包含数组索引的参数,您可以使用该参数将其索引到headings数组中,并将其作为每行的第一个单元格插入
//function to create the table
function createTable(tableData, row_headings) {
var table = document.createElement('table');
var row = {};
var cell = {};
tableData.forEach(function(rowData, i) {
row = table.insertRow(-1);
cell = row.insertCell();
cell.textContent = row_headings[i];
rowData.forEach(function(cellData) {
cell = row.insertCell();
cell.textContent = cellData;
let cellVal = cellData;
//make cells different shades of green and red for pos/neg (based on %)
if (cellVal > 0) {
cell.style.backgroundColor = '#00e100';
} else if (cellVal < 0) {
cell.style.backgroundColor = 'red';
}
});
});
document.body.appendChild(table);
}
createTable(transpose_array, price_array);
//用于创建表的函数
函数createTable(tableData,行标题){
var table=document.createElement('table');
var行={};
var-cell={};
tableData.forEach(函数(rowData,i){
行=table.insertRow(-1);
cell=row.insertCell();
cell.textContent=行标题[i];
rowData.forEach(函数(cellData){
cell=row.insertCell();
cell.textContent=cellData;
设cellVal=cellData;
//为pos/neg设置不同深浅的绿色和红色单元格(基于%)
如果(cellVal>0){
cell.style.backgroundColor='#00e100';
}else if(cellVal<0){
cell.style.backgroundColor='红色';
}
});
});
document.body.appendChild(表);
}
createTable(转置数组、价格数组);
列标题从何而来?只需在添加tableData
内容的循环之前向表中添加一行即可。我向顶部的矩阵中添加了一行,如下所示:transpose\u array.unshift(dates\u arr)这只是在所有日期的顶部添加了另一行。我认为这是您想要的。第一行没有绿色或红色背景色。哦,不,对不起。我想在第一个数字的左边加一列,它应该包含什么,数组索引?