首页 > 解决方案 > 在使用 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

标签: javascriptif-statement

解决方案


问题似乎是您的Math.floor(num * 100 ) / 100 == Math.floor(num)条件评估为true即使num具有非常小的十进制值 - 例如 1.000000007。

num您可以通过直接比较其舍入值来避免该问题:

if (num == Math.floor(num) && pause < 50) {

那样比较,除非num是整数,否则条件不会是true


推荐阅读