如果函数返回true,则在if条件下执行命令

时间:2016-12-18 09:24:53

标签: javascript

以下是代码。 现在我想执行一个特殊命令如果函数返回true。 每当我在""下调用函数时,特殊命令总是在做他的工作。



// You are trapped. Don't move, it'll be painful.
// Attack ogres only when they're within reach.
// This function checks if the enemy is in your attack range.
// The function returns a boolean value:  true or false
function inAttackRange(enemy) {
    var distance = hero.distanceTo(enemy);
    // Almost all swords have attack range of 3.
    if (distance <= 3) {
        return true;
    } else {
        return false;
    }
}
while (true) {
    // Find the nearest enemy and store it in a variable.
    var enemy = hero.findNearestEnemy();
    // Call inAttackRange(enemy), with the enemy as the argument
    // and save the result in the variable canAttack.
    var canAttack = inAttackRange(enemy);
    // If the result stored in canAttack is true, then attack!
    if (canAttack) {       
        
            hero.attack(enemy);
        }
    }
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您的代码出现语法错误。这是工作脚本(可能不起作用,因为某些功能和变量,如“o.findNearestEnemy()”或“英雄”不存在)

// You are trapped. Don't move, it'll be painful.
// Attack ogres only when they're within reach.
// This function checks if the enemy is in your attack range.
// The function returns a boolean value:  true or false
function inAttackRange(enemy) {
    var distance = hero.distanceTo(enemy);
    // Almost all swords have attack range of 3.
    if (distance <= 3) {
        return true;
    } else {
        return false;
    }
}
while (true) {
    // Find the nearest enemy and store it in a variable.
    var enemy = hero.findNearestEnemy();
    // Call inAttackRange(enemy), with the enemy as the argument
    // and save the result in the variable canAttack.
    var canAttack = inAttackRange(enemy);
    // If the result stored in canAttack is true, then attack!
    if (canAttack) {       
        
            hero.attack(enemy);
    }
}