我刚开始学习javascript前几天我想创建一个表格,列出数字1到20以及它们的正方形和立方体,但我无法创建它。任何人都可以帮助我吗?
这是我的代码:
<!DOCTYPE html>
<html>
<body>
<table id="mytable"></table>
<script>
var number = new Array(20);
for(var i =0; i<number.length; i++)
{
number[i] = i+1;
}
var table = document.getElementById("mytable");
var caption = table.createCaption();
caption.appendChild(document.createTextNode("cube and square"));
var thead = table.createTHead();
var tbody = table.createTBody();
var thr = thead.insertRow(-1);
var thr_d0 = thr.insertCell(-1);
thr_d0.appendChild(document.createTextNode("num"));
var thr_d1 = thr.insertCell(-1);
thr_d1.appendChild(document.createTextNode("square"));
var thr_d2 = thr.insertCell(-1);
thr_d2.appendChild(document.createTextNode("cube"));
var cube = new Array();
var square = new Array();
for(var i = 0; i < number.length; i++) {
cube[i] = Math.pow(number[i],3);
square[i] = Math.pow(number[i],2);
var tbr = tbody.insertRow(-1);
var tbr_d0 = tbr.insertCell(-1);
tbr_d0.appendChild(document.createTextNode(square[i]));
var tbr_d1 = tbr.insertCell(-1);
tbr_d1.appendChild(document.createTextNode(cube[i]);
}
</script>
</body>
</html>
答案 0 :(得分:0)
我认为使用数组会使问题过于复杂。相反,只需使用for
循环并使用基本算法插入值:
<table id="myTable"></table>
<script>
//assign the table to a variable
var table = document.getElementById("myTable");
//title the different columns with number, square, and cube
var head = table.insertRow(0);
head.insertCell(-1).innerHTML = "number";
head.insertCell(-1).innerHTML = "square";
head.insertCell(-1).innerHTML = "cube";
//run a for loop to put the squares and cubes of 1 to 20
for (var i = 1; i < 21; i++){
var holder = table.insertRow(-1);
holder.insertCell(-1).innerHTML = i;
holder.insertCell(-1).innerHTML = (i*i);
holder.insertCell(-1).innerHTML = (i*i*i);
}
</script>