以下带注释的 JavaScript 代码创建一个简单的计时器,出于 MWE 的考虑,该计时器会显示在控制台日志中。我试图解释这段代码的每一点,但我对第 2 节和第 10 节中的作业细节感到困惑。我谦虚地请求帮助填补缺失的部分。
//1-Create a function "startTimer" with parameter "duration"
function startTimer(duration) {
//2-Declare a variable "timer" with some strange comma separated assignment (HELP HERE)
var timer = duration, minutes, seconds;
//3-Declare an unassigned variable "output"
var output;
//4-setInterval, which has the syntax *setInterval(function, milliseconds, param1, param2, ...)* indicated that the code below will be performed every interval of 1000 ms, or every one second.
setInterval(function () {
//5-Assign variable "minutes" the value of timer/60 and has radix (base) 10.
minutes = parseInt(timer / 60, 10);
//6-Assign variable "seconds" the value of timer mod 60 and has radix (base) 10.
seconds = parseInt(timer % 60, 10);
//7-Assign variable "minutes" to the value of "0" + minutes if minutes < 10, or minutes if not. This is accomplished with the ternary operator "?", which has syntax *condition ? exprT : exprF*
minutes = minutes < 10 ? "0" + minutes : minutes;
//8-Assign variable "seconds" in the same way minutes are assigned, which adds a leading zero if the value is <10.
seconds = seconds < 10 ? "0" + seconds : seconds;
//9-Assign variable "output" to minutes concatenated with ":" concatenated with seconds
output = minutes + ":" + seconds;
//10-If the value of timer incremented downward by one (HELP ON WHAT THAT MEANS) is less than zero then assign variable "timer" to the value of variable "duration", which will be (HELP ON WHERE DURATION GETS ITS VALUE).
if (--timer < 0) {
timer = duration;
}
//11-Output the formatted timer to the console log
console.log(output);
//12-End the function performed in setInterval. Also set the interval in which the function is repeated to 1000 ms (the second argument in the setInterval function).
}, 1000);
//13-End of function startTimer
}
最佳答案
第 2 部分
var timer = duration, minutes, seconds;
这一行声明了 3 个变量:timer
, minutes
,和seconds
.
它还初始化变量 timer
值为 duration
.
第 10 节
if (--timer < 0) {
timer = duration;
}
--timer
语法意味着计时器的值首先减 1,然后读取其值 if (timer < 0)
比较。
duration
变量是 startTimer
的参数函数,因此它的值是由函数的用户在此代码的范围之外分配的。
关于javascript - 简单的 Javascript 时钟变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55711589/