javascript - Javascript将行标题从数组中添加到表中?
问题描述
我有一个填充表格的二维数组。有没有办法一直向左插入一列?
//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);
由于颜色条件,我不想向表中添加值,我只想使用我拥有的数组中的值向表的 y 轴上的每一行添加标题。
解决方案
回调获取包含数组索引的forEach()
第二个参数,您可以使用它来索引标题数组,并将其作为每行中的第一个单元格插入。
//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);
推荐阅读
- python - 我可以为 Cloud9 的 Lambda 函数设置 PYTHONPATH 吗?
- laravel - 如何在axios.get之外调用变量?它没有给我任何结果
- c++ - 如何检查文件中是否已存在变量值?
- php - 如何使用 cmd 提示符获取开发服务器的文档根目录?
- scala - 给定Scala中的特定条件,如何组合两个数据框中的行?
- postgresql - 对 WITH 变量执行选择查询
- python - BeautifulSoup html.parser 不显示所有源代码
- django - django post api 通过邮递员
- nativescript - Nativescript Vue:将小屏设计与大屏相匹配?
- python - Python - 遍历用户输入的数字,计算并输出输入的值