Webデザインの勉強と製作 | あかとんぼ

フェリカテクニカルアカデミーの学習をベースに、Webについての勉強と製作の過程をまとめています。

[JavaScript]②ブラウザに表示する

  • ブラウザに文字を表示
  • toFixed
  • 性別と年齢を入力したら厄年かどうか表示するプログラム(if文使用)

ブラウザに文字を表示

window.document.write
var hoge = 'こんにちは';
window.document.write('Hello' + 'World' + hoge);
</script>
警告ダイアログに表示
  • windowは省略可能。
  • 改行タグは使えない。¥nで改行できる
window.alert(‘ありがとう¥nございました’);
</script>
ユーザに確認を求めるダイアログボックス
  • 変数=confirm( メッセージ );
  • OKで真、キャンセルで偽の値を返す
var man = confirm('あなたは男ですか?');
console.log(man);
</script>
ユーザーにデータを入力してもらうダイアログボックス
  • prompt( メッセージ );
  • 変数 = prompt( メッセージ, デフォルトの値 );
文字列を数値に変換
  • parseInt(変換する文字列);
var num1, num2 = 10;
num1 = prompt('数字を入力','60');
//promptで返される値は文字列
document.write(num1+num2);
//num2を数値に変換
console.log(parseInt(num1) + num2);
</script>


小数点を丸める

  • .toFixed()
  • 四捨五入を行う
var a = 10;
var b = 3;
var x = a/b;
document.write(x.toFixed(2));//下2桁まで表示
</script>

課題

 性別と年齢を入力したら厄年かどうか表示するプログラム(if文使用)

var man;
var age;
man = confirm('あなたは男性ですか?');
age = prompt('半角数字で年齢を入力してください','20');
age = parseInt(age);
if(man){
     if( age==25 || age==42 || age==61){
       window.document.write( age+'才の男性は本厄の年です');    
     }else{
       window.document.write( age+'才の男性は厄年ではありません');    
     }
}else{
       if( age==19 || age==33 || age==37){
       window.document.write( age+'才の女性は本厄の年です');    
     }else{
       window.document.write( age+'才の女性は厄年ではありません');    
     }
}
</script>