ウェブ学のすすめ

Study of Web Design & Programing

配列の演算|実践課題D

コード

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>配列</title>
<style>
body {
    font-family:
	"ヒラギノ角ゴ Pro W3",
	"Hiragino Kaku Gothic Pro",
	"メイリオ", 
	Meiryo, Osaka, 
	"MS Pゴシック", 
	"MS PGothic", 
	sans-serif}
table,th,td {
    border: 1px solid #000;
    border-collapse: collapse;
}
th {
    background-color: #eee;
    width: 100px;
}
td {
    text-align: center;
    width: 100px;
}
</style>
<script>
var keisan = [
    {a:5,b:33},
    {a:12,b:14},
    {a:18,b:65}
];

function Kakezan(i){
    var result = keisan[i].a*keisan[i].b;
    alert("答えは、"+result+"です。");
}
</script>
</head>
<body>
<h1>配列の計算</h1>

<table>
    <tr><th>添字</th><th>a</th><th>b</th><th>a×bを計算</th></tr>
    <tr><th>0</th><td>5</td><td>33</td><th><button onClick="Kakezan(0)">計算結果</button></th></tr>
    <tr><th>1</th><td>12</td><td>14</td><th><button onClick="Kakezan(1)">計算結果</button></th></tr>
    <tr><th>2</th><td>18</td><td>65</td><th><button onClick="Kakezan(2)">計算結果</button></th></tr>
</table>
</body>
</html>

表組みもJavaScriptで記述したバージョン

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>配列</title>
<style>
body {
    font-family:
	"ヒラギノ角ゴ Pro W3",
	"Hiragino Kaku Gothic Pro",
	"メイリオ", 
	Meiryo, Osaka, 
	"MS Pゴシック", 
	"MS PGothic", 
	sans-serif}
table,th,td {
    border: 1px solid #000;
    border-collapse: collapse;
}
th {
    background-color: #eee;
    width: 100px;
}
td {
    text-align: center;
    width: 100px;
}
</style>
<script>
var keisan = [
    {a:5,b:33},
    {a:12,b:14},
    {a:18,b:65}
];

function Kakezan(i){
    var result = keisan[i].a*keisan[i].b;
    alert("答えは、"+result+"です。");
}
</script>
</head>
<body>
<script>
document.write("<h1>配列の計算<\/h1>");

document.write("<table>");
document.write("<tr><th>添字<\/th><th>a<\/th><th>b<\/th><th>a×bを計算<\/th><\/tr>");


for(var i=0; i<keisan.length; i++){
    document.write("<tr>");	
    document.write("<th>",i,"<\/th>");	
    document.write("<td>",keisan[i].a,"<\/td>");
    document.write("<td>",keisan[i].b,"<\/td>");
    document.write("<td><button onClick='Kakezan(",i,")'>計算結果</button><\/td>");
    document.write("<\/tr>");	
}
document.write("<\/table>");
</script>
</body>
</html>

ポイント

  • 引数を配列の要素番号として利用する