
50代からのHTML / CSS / JavaScriptチャレンジ No.123 変数・定数
こんにちは〜今日はプログラミングでよく出てくる、変数と定数について学習します。そしたら、新規ファイルを作成して始めます。value.htmlというファイルを作って、template.htmlからコピー&ペースト。そしたら、これまでと同様、bodyタグ内にscriptタグを記述してプログラムを書いていく。

そしたら、保存&リロード。


ディスプレイに表示されてるね^^で、これを自動で計算させたい場合どうするか。
そしたら、770円のところを以前やった文字列連結で書いてみる。

これで保存&リロード

まぁ、誤差は出るけど、770円として計算はできてるね。だけど、700円の時ならいいけど、他の金額になると使えないよね。こんな時に便利なのが変数になるよね。(Swiftの勉強の時に出てきた!)
javascriptではどう書くのかやってみる。

constっていうのを使うんだね。そのconstの変数名にpriceとつけて、それを使う。そしたら、保存&リロード。あっ700円を600円にしてからね。

ちゃんと計算されてるね〜^^ちなみにconst price = 600;の=は、代入の意味ね。算数のイコールとはちょっと違うからね。右の値を左に代入って意味。
で、これを使うと最初の600円のところにもこれが使える。

こーゆーことね。それじゃ保存&リロードしてみる。

変化はないけど、その分、ちゃんと計算されてるってことね。これの何が便利かっていうと600のところを500に変えたら、500円の計算をしてくれるのよ。

そしたら、保存&リロード

変わってるね^^
1.1のところも変えることができるよ〜
const tax = 1.1;というのを加える。

こうすれば、将来、消費税が変わっても、1.1のところだけ変えればOKってなるよね。
しかも変数(定数)名にpriceとかtaxって名前をつければ、わかりやすくもなるよね。
そしたら、保存&リロード

それじゃ今日はここまで〜明日はもう少し詳しく見てくよ〜^^
いいなと思ったら応援しよう!
