javascript - 将 boolean 值从 true 更改为 false,然后使用 jquery 在 if() 中使用它

标签 javascript jquery if-statement boolean var

我尝试了多种方法来实现从 boolean 值到 if 语句的输出。不知怎的,我做错了。我可以更改 boolean 值并 console.log 它,所以这应该是正确的。然后我尝试在 if 语句中使用它,但不知何故它被忽略并且没有给出预期的结果。 这是我的代码:

    var heroVelX = game.currentHero.GetLinearVelocity().x;
    var heroVelY = game.currentHero.GetLinearVelocity().y;
    var speed = Math.sqrt(Math.pow(heroVelX, 2) + Math.pow(heroVelY, 2));
    var moveOn = "";

    function delay(){   
        moveOn = Boolean(speed<1.5);
        console.log("Speed = " + speed + "  " + moveOn);    
    };  

    setTimeout(delay, 3500);

    // These are the conditions I have tried using. I can see in console.log that the value is changed. But somehow it is ignored? All the other conditions are accepted in the if-statement.       
    // moveOn ===!false
    // moveOn == true

    if(!game.currentHero.IsAwake() || moveOn === !false || heroX<0 || heroX >game.currentLevel.foregroundImage.width ){
            // then delete the old hero
            box2d.world.DestroyBody(game.currentHero);
            game.currentHero = undefined;
            // and load next hero
            game.mode = "load-next-hero";
        }

有人可以告诉我我做错了什么吗?

最佳答案

你做错了几件事......

首先,将 var 定义为 String,然后将其更改为 boolean,这是很糟糕的。

其次,将 boolean 值放入不同的日志中,并使用 dir 代替。

if 语句太困惑了。

并且无需转换为 boolean 值。

看看这个:

var heroVelX = game.currentHero.GetLinearVelocity().x;
var heroVelY = game.currentHero.GetLinearVelocity().y;
var speed = Math.sqrt(Math.pow(heroVelX, 2) + Math.pow(heroVelY, 2));
var moveOn = false;

function delay(){   
    moveOn = (speed<1.5) ? true : false;
    console.log("Speed = " + speed);
    console.dir(moveOn);


};  

setTimeout(delay, 3500);

if(!game.currentHero.IsAwake() || moveOn || heroX<0 || heroX >game.currentLevel.foregroundImage.width ){
        // then delete the old hero
        box2d.world.DestroyBody(game.currentHero);
        game.currentHero = undefined;
        // and load next hero
        game.mode = "load-next-hero";
    }

关于javascript - 将 boolean 值从 true 更改为 false,然后使用 jquery 在 if() 中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26403466/

相关文章:

javascript - 在 1 到 100 之间随机 10 个数字的最佳方法没有 javascript 中的欺骗?

javascript - 将 jQuery 代码添加到 PHP 字符串

java - 在运行配置中使用字符串作为参数并在 if 语句中使用它

javascript - 如何在 jquery 中向 'this' 上面的总体类添加一个类

java - 如何使用 JTextFields 中的 If 语句

java - 决策表或 if-else 语句

javascript - 如何为动态生成的输入框设置onclick属性

javascript - 使用 ng-model 获取 <li> 值

javascript - 使用 MongoDB $setEquals 时引号中的 ID

javascript - TinyMCE 3 高级主题到 TinyMCE 4