【JavaScript】for文のサンプル
数列の合計値を計算
最初の数から最後の数までを全て合計する。
最初の数:
最最後の数:
■HTML
1 2 3 4 5 |
最初の数から最後の数までを全て合計する。<br/> 最初の数:<input id="sample_start" value="1"/><br/> 最最後の数:<input id="sample_end" value="50"/><br/> <button onclick="calcTotal()">計算</button> <p id="sample_total"></p> |
■JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<script> function calcTotal() { //入力値のチェック var startVal = document.getElementById("sample_start").value; var endVal = document.getElementById("sample_end").value; if ( parseInt(startVal) >= parseInt(endVal) ) { window.confirm("最初の数は最後の数よりも小さい数を指定して下さい"); return; } //合計値を計算 var totalVal = 0; for (var i = startVal ; i <= endVal ; i++ ) { totalVal += parseInt(i); } document.getElementById("sample_total").textContent = "合計値は" + totalVal + "です。"; } </script> |
![]() |