配列

配列とは

変数と同じ箱の役割がありますが、変数と違うところは複数の値を入れることができることです。仕切りのある箱と考えます。

宣言の方法

var 変数 = new Array ( 値1, 値2, ・・・ );

変数:配列名

new:new演算子

値:整数、文字、関数、オブジェクト

※値は省略可能でArray()とできます。

 

基本形

var fruit = new Array('りんご', 'バナナ', 'みかん', 'もも')

 

省略形

var fruit = ['りんご', 'バナナ', 'みかん', 'もも']

 

コンストラクタ関数を使用した記述

var fruit = new Array(4);

fruit[0] = 'りんご';

fruit[1] = 'バナナ';

fruit[2] = 'みかん';

fruit[3] = 'もも';

※Array(4)の4は省略可能でArray()とできます。

 

配列の練習1

<script>
var fruit = new Array();
fruit[0] = 'りんご';
fruit[1] = 'バナナ';
fruit[2] = 'ミカン';
fruit[3] = 'もも';
fruit[4] = 'メロン';
fruit[5] = 'スイカ';
console.log(fruit.length);
console.log(fruit);
console.log(fruit[0]);
console.log(fruit[1]);
console.log(fruit[2]);
console.log(fruit[3]);
console.log(fruit[4]);
console.log(fruit[5]);

for (i = 0; i<fruit.length; i++) {
document.write('fruit['+i+']='+fruit[i]+'<br>');
}
</script>

結果

f:id:develog:20160901235741g:plain

配列の練習2

<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>配列</title>
</head>
<style>
table {
width: 500px;
border-collapse: collapse;
border-spacing: 0;
}
th {
height: 25px;
}
tr:first-child,th:first-child {
background-color: #EEE;
}
td {
text-align: right;
}
</style>

<body>
<h3>単価×個数の一覧表</h3>
<table border="1">
<tr>
<th>個数</th><th>商品A</th><th>商品B </th><th>商品C</th><th>商品D</th><th>商品E</th>
</tr>
<script>
var tanka = new Array();
tanka[0] = 300;
tanka[1] = 450;
tanka[2] = 520;
tanka[3] = 700;
tanka[4] = 850;

for(i = 1; i <= 10; i++){
document.write('<tr>');
document.write('<th>'+i+'</th>');
for(j = 0; j < tanka.length; j++){
document.write('<td>'+tanka[j]*i+'円</td>');
}
document.write('</tr>');
}

</script>
</body>
</html>

結果

f:id:develog:20160902000033g:plain

 

配列の練習3 

<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>配列</title>
</head>
<style>
table {
width: 600px;
border-collapse: collapse;
}
tr {
height: 24px;
}
tr:first-child,th:first-child {
background-color: #DDD;
}
</style>

<body>
<h3>主要通貨の為替レート</h3>
<table border="1">
<tr>
<th>個数</th><th>米ドル</th><th>ユーロ</th><th>人民元</th><th>ポンド</th>
</tr>
<script>
var money = new Array();
money[0] = 103;
money[1] = 115;
money[2] = 15;
money[3] = 135;

document.write('<tr>');
document.write('<th>1</th>');
for(i = 0; i<money.length; i++) {
document.write('<th>'+money[i]+'円</th>');
}
document.write('</tr>');

for(i = 5; i <=100; i+=5 ) {
document.write('<tr>');
document.write('<th>'+i+'</th>');
for(j = 0; j < money.length; j++) {
document.write('<th>'+money[j]*i+'円</th>');
}
document.write('</tr>');
}
</script>
</body>
</html>

結果

f:id:develog:20160902000145g:plain