javascript - 在使用 if 语句暂停之前,数字会增加吗?
问题描述
我希望当变量num
达到整数时数字停止。暂停工作正常,但它上升 0.01 然后暂停。该语句每帧运行一次(通过requestAnimationFrame
)。
if (Math.floor(num * 100) / 100 == Math.floor(num) && pause < 50) {
pause += 1;
} else {
pause = 0;
num += 0.01;
}
完整的代码块在 GitHub 上:
https ://github.com/BootLegAidan/Geometrical-Thing/blob/master/Update.js
解决方案
问题似乎是您的Math.floor(num * 100 ) / 100 == Math.floor(num)
条件评估为true
即使num
具有非常小的十进制值 - 例如 1.000000007。
num
您可以通过直接比较其舍入值来避免该问题:
if (num == Math.floor(num) && pause < 50) {
那样比较,除非num
是整数,否则条件不会是true
。