我正在尝试构建并显示基于数组的表。我已经四处搜索了一段时间,似乎无法找到答案,说明为什么我的代码无法正常工作。
它是一个简单的函数调用,数组通过函数参数传入,但由于某种原因它出现未定义,因为它似乎没有传递给函数参数。
我的代码的基本摘要如下:
<div id="myDiv"></div>
<script>
function myFunction(tableData){
var table = document.createElement('table');
var tableBody = document.createElement('tbody');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
};
var array1 = {key1:"value1",key2:"value2",key3:"value3"};
document.getElementById("myDiv").innerHTML = myFunction(array1);
</script>
编辑:这个问题已经解决了。谢谢你的评论!
答案 0 :(得分:0)
你想用这条线做什么
Type Date Ref Qty OnHand
Bill 4/15/2017 01 36 36
Invoice 4/16/2017 10 -6 30
Invoice 4/17/2017 12 -5 25
我无法从您的函数中找到任何设置div的内部html的返回。
document.getElementById("myDiv").innerHTML = myFunction(array1);
并且您的数组是一个对象。
首先尝试解决这些问题。
尝试这样做..
var array1 = {key1:"value1",key2:"value2",key3:"value3"};
答案 1 :(得分:0)
执行类似
的操作for(var i in array1) {
console.log(i); //this will print key1, key2...
console.log(array1[i]); //this will print value1, value2...
}
您获得的错误是因为您的数据是javascript对象,而不是javascript数组。所以forEach
不会工作。
答案 2 :(得分:0)
基本上,你需要
appendChild
来获取分配给div的表,因为您正在使用DOM元素而不使用字符串(字符串与innerHTML
一起使用)。
function myFunction(tableData) {
var table = document.createElement('table');
var tableBody = document.createElement('tbody');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
return table;
}
var array1 = [["value1", "value2", "value3"], ["value4", "value5", "value6"], ["value7", "value8", "value9"]];
document.getElementById("myDiv").appendChild(myFunction(array1));
<div id="myDiv"></div>