【问题标题】:Changing boolean from true to false and use it in if() afterward using jquery将布尔值从 true 更改为 false,然后使用 jquery 在 if() 中使用它
【发布时间】:2014-12-11 18:21:24
【问题描述】:

我尝试了几种方法来实现从布尔到 if 语句的输出。不知何故我做错了。我能够更改布尔值和 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";
        }

谁能告诉我我做错了什么?

【问题讨论】:

  • setTimeout(delay, 3500); 这行将运行,然后 继续 到下一个(您的条件)moveOn 仍然是 "",因为 delay() 尚未执行。
  • 我怎样才能停止程序直到 moveOn 发生变化?还是有其他解决方案?
  • setTimeout 安排对delay() 的调用,因此如果您希望在延迟 之后运行,请将其放入delay()
  • 我不能设置moveOn = false;吗?

标签: javascript jquery if-statement boolean var


【解决方案1】:

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

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

其次,将您的布尔值放入不同的日志中,并改用 dir。

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 = 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";
    }

【讨论】:

  • 我看到了声明字符串然后将其更改为布尔值的意义。 .dir 对我来说是新的并且没有给我任何反馈?如何改进 if 语句?我尝试使用您的建议,但它没有解决我的问题?
  • 使用 .dir 而不是 .log 的想法是因为 .log 会将值转换为字符串,而转换为布尔值的字符串是您看不到的空字符串。 .dir 将向您显示 var 的实际值。另请参阅我的代码。我在 if 语句中删除了 moveOn 的所有运算符。一个布尔值本身就足以在 if 语句中为真/假。你现在有什么行为?
  • 我删除了 delay() 函数,因为它会中断布尔值。它不会传递它。这不是最佳的,但没关系。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多