JavaScript 基礎②

  • prompt( メッセージ );はダイアログボックス内の記述と入力欄の初期値を入力できる(入力しなくてもいい)。
<script>
  var rate = 100;
  var doll, yen;
  
  doll = prompt('金額をドルで入力して下さい','半角数字で入力して下さい');
  yen = doll * rate;
    alert (yen + '円です');/* 「金額をドルで入力して下さい」と初期値に
半角数字で入力して下さいと表示  */
</script>
  • confirm( メッセージ );Yesかその他で分ける
<script>
  var man;  //男性かどうか?
  man = confirm('あなたは男性ですか?');
</script>
  • num = parseInt(a);数字として判断される
<script>
/* 標準体重計算プログラム 
/* 最終修正日 : 2013.07.25
*/

  var height;
  var weight;
  var ans;
  
  height = prompt ('身長(cm)を入力してください','半角英数字で');
  height = parseInt (height);
  
  weight = ( height - 100) * 0.9;
  weight = parseInt( weight );
  
  ans = '身長が' + height + 'cmの人の標準体型は' + weight + 'kgです。';
  document.write( '<h1>'+ans+'</h1>' );
  
</script>
  • if(条件式){条件を満たす場合に実行する処理}else{条件を満たさない場合に実行する処理}
<script>
  var height;
  var wight;
  var man;//男性かどうか
  
  //男性か女性かを入力
  man = confirm('あなたは男性ですか?');
  
  //身長を代入する
  height = prompt('身長を入力して下さい','半角数字で入力');
  height = parseInt(height);
  console.log(height);
  
  //計算を行う
  if(man){
	  weight = (height - 80)*0.7;
  }else{
	  weight = (height - 70)*0.6;
  }
  weight = parseInt(weight);
  console.log(weight);
  
  //結果を表示する
  document.write('身長が',height,'cmの');
  if(man){
  document.write('男性の標準体重は');
  }else{
  document.write('女性の標準体重は');
  }
  document.write( weight,'kgです。');
  </script>