所以我在JavaScript中使用这个2D数组并尝试使用innerHTML或document.write打印其元素,但在for循环中使用innerHTML会覆盖彼此之间的所有元素。使用document.write将所有元素放在一行中(我不会连续超过3个元素),所以请帮助我找到一种方法! (我知道我的解决方案是错误的,但我只是想表明我在想什么)
const myData = function(){
return
[[{"number":1,"name":"Jack","day":"Sat"},
{"number":2,"name":"Max","day":"Sun"}],
[{"number":3,"name":"Al","day":"Mon"},
{"number":4,"name":"Jacky","day":"Tues"}
{"number":5,"name":"Daniel","day":"Wed"}]];
};
var array = myData();
var len = array.length;
var i, j;
for (i=0; i<len; i++){
for (j=0; j<3; j++){
document.getElementByID(demo).innerHTML = array[i][j].number;
document.getElementByID(demo).innerHTML = array[i][j].day;
document.getElementByID(demo).innerHTML = array[i][j].name;
} }
答案 0 :(得分:1)
您可以连接innerHTML,因此它将具有旧值和新值。
在=:
之前加上一个+document.getElementByID(demo).innerHTML += array[i][j].number;
document.getElementByID(demo).innerHTML += array[i][j].day;
document.getElementByID(demo).innerHTML += array[i][j].name;