trueまたはfalseを返す:
| 比較演算子 | 意味 |
== | 左辺と右辺が等しい |
|---|---|
!= | 式が等しくない |
> | 左辺が大きい |
>= | 左辺が大きいか等しい |
< | 右辺が大きい |
<= | 右辺が大きいか等しい |
trueとfalseの値を取る)を組み合わせて、1つの論理式を組み立てるために、次のような論理演算子を使う:
論理演算子を複数使った論理式では、式をカッコ ( と ) で囲んで意味をはっきりさせること。
| 論理演算子 | 意味 | 備考 |
&& |
左右の条件式の論理積を返す | 両方がtrueの場合にのみtrue |
|---|---|---|
|| |
左右の条件式の論理和を返す | 一方または両方がtrueの場合にtrue |
! |
条件式の値の否定を返す | trueならfalse、falseならtrue |
x, yに対して次のように使う:
| 論理式 | 論値値 |
2 < x && x < 13 | true |
x > 4 && y < 5 | true |
x < 1 || 5 < x | true |
!(x > 3) | false |
(x > 5 && y < 2) || x == 10 | true |
x == 3 || y > 10 || x < y | false |
| グループ名 | メンバ |
| 春 | 3月、4月、5月 |
| 夏 | 6月、7月、8月 |
| 秋 | 9月、10月、11月 |
| 冬 | 12月、1月、2月 |
| 平日 | 月曜〜金曜 |
| 休日 | 土曜、日曜 |
Dateオブジェクトを使った次のスクリプトを利用して、季節や平日・休日を判断するとを考えよう。
getMonth()、getDay()メソッドが返す値には表のような換算が必要であることは既に説明した。
<script type="text/javascript"> <!-- var today = new Date(); var year = today.getYear(); var month = today.getMonth(); var date = today.getDate(); var day = today.getDay(); .... </script> |
|
break;を効果的に利用していることに注意せよ。
| if文を使った場合 | switch文を使った場合 |
<script type="text/javascript">
<!--
var today = new Date();
var year = today.getYear();
var num_month = today.getMonth();
var month;
var date = today.getDate();
var num_day = today.getDay();
var day;
....
....
if (0 <= num_day && num_day <= 4)
document.write("今日は平日だ", "<br>")
else if (5 <= num_day && num_day <= 6)
document.write("今は休日だ", "<br>");
....
....
// -->
</script>
|
<script type="text/javascript">
<!--
var today = new Date();
var year = today.getYear();
var num_month = today.getMonth();
var month;
var date = today.getDate();
var num_day = today.getDay();
var day;
....
....
switch (num_day) {
case 0:
case 1:
case 2:
case 3:
case 4:
document.write("今日は平日だ", "<br>");
break;
case 5:
case 6:
document.write("今は休日だ", "<br>");
}
....
....
// -->
</script>
|