前提・実現したいこと
こちらのページでストップウォッチを作成しています。
時間を計算する部分で、"1%60"のような剰余の計算が出てくるのですが、なぜ割れない数字が余りの値を返すかわかりません?一体どのような計算が行われいるのでしょうか?
以下のコードのMath.floorの後ろの部分です。
なぜこのような計算をすると時間/分数/秒数が求められるのでしょうか?
該当のソースコード
Javascript
1// Define a counter variable for the number of seconds and set it to zero. 2let secondCount = 0; 3 4// Define a global to store the interval when it is active. 5let stopWatch; 6 7// Store a reference to the display paragraph in a variable 8const displayPara = document.querySelector('.clock'); 9 10// Function to calculate the current hours, minutes, and seconds, and display the count 11function displayCount() { 12 // Calculate current hours, minutes, and seconds 13 let hours = Math.floor(secondCount / 3600); 14 let minutes = Math.floor((secondCount % 3600) / 60); 15 let seconds = Math.floor(secondCount % 60) 16 17 // Display a leading zero if the values are less than ten 18 let displayHours = (hours < 10) ? '0' + hours : hours; 19 let displayMinutes = (minutes < 10) ? '0' + minutes : minutes; 20 let displaySeconds = (seconds < 10) ? '0' + seconds : seconds; 21 22 // Write the current stopwatch display time into the display paragraph 23 displayPara.textContent = displayHours + ':' + displayMinutes + ':' + displaySeconds; 24 25 // Increment the second counter by one 26 secondCount++; 27} 28 29// Store references to the buttons in constants 30const startBtn = document.querySelector('.start'); 31const stopBtn = document.querySelector('.stop'); 32const resetBtn = document.querySelector('.reset'); 33 34// When the start button is pressed, start running displayCount() once per second using displayInterval() 35startBtn.addEventListener('click', () => { 36 stopWatch = setInterval(displayCount, 1000); 37 startBtn.disabled = true; 38}); 39 40// When the stop button is pressed, clear the interval to stop the count. 41stopBtn.addEventListener('click', () => { 42 clearInterval(stopWatch); 43 startBtn.disabled = false; 44}); 45 46// When the reset button is pressed, set the counter back to zero, then immediately update the display 47resetBtn.addEventListener('click', () => { 48 secondCount = 0; 49 displayCount(); 50}); 51 52// Run displayCount() once as soon as the page loads so the clock is displayed 53displayCount();
試したこと
たとえば、secondCountの値が1なら、1割る60の余りが1になるということですよね?
60割る3600の余りを60で割ると1になるってことですよね?
これがさっぱりわからないのです。
僕の認識では、1は60では割れないので余りは出ずに0になる。と思うんですが、%の扱いについて何か認識違いをしているのかもしれません。
%演算子のページも読みましたが、明確な答えは得られませんでした。
加えてこの計算が理解できたとして、何故このような計算をすると時間/分数/秒数が求められるのかもよくわかりません。
ご教授のほど、よろしくお願いします。
補足情報(FW/ツールのバージョンなど)
ここにより詳細な情報を記載してください。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/08/08 14:30
2019/08/09 01:25