WEB、始めました

半年間WEB制作の学校に通います。その記録。

34日目 DOM

配列を使った掛け算
http://tototo.webcrow.jp/script/0310/array03.html

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>配列を使った掛け算</title>
<style>

table {
  border: 1px solid #666;
  border-collapse: collapse;
}
th,td {
  border: 1px solid #666;
  width: 100px;
  padding: 5px;
  text-align: center;
}

th {
  background: #f6f6f6;
}

</style>
<script>
var a = new Array(3);
var b = new Array(3);
var kai;
a[0] = 5;
a[1] = 12;
a[2] = 18;
b[0] = 33;
b[1] = 14;
b[2] = 65;

function ans(i) {
  kai = a[i]*b[i];

  alert('答えは' + kai + 'です');
  console.log(a[i]);
  console.log(b[i]);
  console.log(kai);

}
</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><td><button onclick="ans(0)">計算結果</button></td>
</tr><!--ans(引数の番号を使って計算する)-->
<tr>
<th>1</th><td>12</td><td>14</td><td><button onclick="ans(1)">計算結果</button></td>
</tr>
<tr>
<th>2</th><td>18</td><td>65</td><td><button onclick="ans(2)">計算結果</button></td>
</tr>
</table>

</body>
</html>


1年後の曜日を表示する
http://tototo.webcrow.jp/script/0310/array04.html

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>1年後の曜日を表示する</title>
</head>

<body>
<script>
var days = new Array('日','月','火','水','木','金','土');
var today = new Date;  //今日(今現在)の値

today.setFullYear(today.getFullYear() + 1);
//setFullYearで日付指定
console.log( today );
document.write('<h1>一年後は' + days[today.getDay()] +'曜日</h1>');
//days[today.getDay()]の「today」がtoday.setFullYear(today.getFullYear() + 1);になっている
</script>
</body>
</html>


小さい順にsortされる
http://tototo.webcrow.jp/script/0310/array05.html

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>Arrayオブジェクトのsortメソッド</title>
<script>
function compare(a,b) {
  return a - b;//どちらが大きいか比較する関数
}
</script>
</head>

<body>
<script>
var ages = new Array(6,87,4,35,76,9,11,25);
  ages = ages.sort(compare);
  document.write(ages.join(' < '));
</script>
</body>
</html>


連想配列
for~in文

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>連想配列</title>
</head>

<body>
<script>
var colors = new Object();
colors['white'] = '白色';
colors['red'] = '赤色';
colors['green'] = '緑色';
colors['yellow'] = '黄色';

for (var eigo in colors) {
document.write( '<h2>' + eigo + ':' + colors[eigo] + '</h2>' );
}
</script>
</body>
</html>