使用 typeof … != "undefined" 和 clearInterval 的这段代码有什么作用?
What does this code using typeof … != "undefined" and clearInterval do?
为了学校,我需要在 JavaScript 中编写一个游戏,但问题是我不明白这部分代码的含义:
if (typeof game_loop != "undefined") clearInterval(game_loop);
game_loop = setInterval(paint, 60);
如果 game_loop
存在,则停止计时器。
在此之后,将定时器设置为每 60 毫秒执行一次 paint
。
if (typeof game_loop != 'undefined')
如果变量game_loop
不是undefined
clearInterval(game_loop);
清除id为game_loop
的已有区间
game_loop = setInterval(paint, 60);
每 60
毫秒调用 paint
并将间隔 ID 存储在 game_loop
.
中
理想情况下,为了清楚起见,代码应该写成:
if (game_loop !== undefined) {
clearInterval(game_loop);
}
game_loop = setInterval(paint, 60);
typeof xyz !== 'undefined'
用于避免覆盖 window.undefined
时可能出现的错误,但没有人应该覆盖 window.undefined
,所以我不会担心它。
正在检查game_loop
是否存在,如果存在,则清除间隔。然后,它每 60 毫秒进行一次 paint
调用。
为了学校,我需要在 JavaScript 中编写一个游戏,但问题是我不明白这部分代码的含义:
if (typeof game_loop != "undefined") clearInterval(game_loop);
game_loop = setInterval(paint, 60);
如果 game_loop
存在,则停止计时器。
在此之后,将定时器设置为每 60 毫秒执行一次 paint
。
if (typeof game_loop != 'undefined')
如果变量game_loop
不是undefined
clearInterval(game_loop);
清除id为game_loop
game_loop = setInterval(paint, 60);
每 60
毫秒调用 paint
并将间隔 ID 存储在 game_loop
.
理想情况下,为了清楚起见,代码应该写成:
if (game_loop !== undefined) {
clearInterval(game_loop);
}
game_loop = setInterval(paint, 60);
typeof xyz !== 'undefined'
用于避免覆盖 window.undefined
时可能出现的错误,但没有人应该覆盖 window.undefined
,所以我不会担心它。
正在检查game_loop
是否存在,如果存在,则清除间隔。然后,它每 60 毫秒进行一次 paint
调用。