情報処理実習3B(Web)

2018年度 前期 木04 15:15-16:45 瀬田2-119

変数とデータ型

変数

変数の宣言と代入
var 変数名 =;
変数の出力
document.write('文字列' + 変数名 + '文字列);
※文字列の結合は+
var1.html
<!DOCTYPE html>
<html lang="ja">
<head>
   <meta charset="UTF-8" />
   <title>変数1</title>
</head>
<body>
<script>
var str = 'abc';
document.write ('<p>文字列str=' + str + 'です</p>');
</script>
</body>
</html>

コーテーションマーク

ダブルコーテーションとシングルコーテーション
JavaScriptにおいては両者は差はない
ただhtmlはダブルコーテーションを多用するので、バッティングしにくいシングルコーテーションが好まれる。
エスケープ

htmlのダブルコーテーションとJavaScriptのダブルコーテーションがバッティングするときにはhtmlのダブルコーテーションの前にエスケープ文字(\)を置く

JavaScriptがわでシングルコーテーションを使うときには問題ない

var2.html
<!DOCTYPE html>
<html lang="ja">
<head>
   <meta charset="UTF-8" />
   <title>ダブルコーテーションとシングルコーテーション</title>
</head>
<body>
<h1>ダブルコーテーションとシングルコーテーション</h1>
<script>
var str = '文字列';
document.write('<p class="test">' + str + '</p>');
document.write('<p class="test">str</p>');
document.write("<p class=\"test\">str</p>");
</script>
</body>
</html>

データの型

型変換
var str = '2';
var number1 = 2;
var number2 = 1;
number1 + number2は数値型(出力結果は3)
str + number1は文字列型(出力結果は21)
var3.html
<!DOCTYPE html>
<html lang="ja">
<head>
   <meta charset="UTF-8" />
   <title>データの型</title>
   <script>
var today = new Date();
var today_date = today.getDate();
var today_month = today.getMonth();//月は0~11で出力される。ここでは数値型
var today_year = today.getFullYear();
   </script>
</head>
<body>
<script>
document.write('<p>今日は' + today_year + '年' + today_month + 1 + '月' + today_date + '日です(today_monthはこの段階では文字列型に変換済み、ゆえに21月などと表示される)</p>');
document.write('<p>今日は' + today_year + '年' + (today_month + 1) + '月' + today_date + '日です(today_monthを数値型のまま先に計算)</p>');
</script>
</body>
</html>
弱いデータ型
JavaScriptでは変数のデータ型は自動的に変換されるので余り意識しなくても使える(Excelに近い)。
強いデータ型
変数がどのデータ型なのかをあらかじめ宣言して使用する必要がある言語もある(Accessに近い)。