我的if / else语句怎么了?

时间:2013-11-13 21:25:22

标签: javascript if-statement

无法弄清楚我的if / else子句有什么问题。继续给我一个意外的令牌错误。

var creditCheck = function(income) {
    var val = income;
};

if (creditCheck > 100); { 
    return "You earn a lot of money! You qualify for a credit card.";
} else {
    return "Alas, you do not qualify for a credit card. Capitalism is cruel like that.";
}

console.log(creditCheck(75));

3 个答案:

答案 0 :(得分:6)

您的函数creditCheck不会返回值。您必须将其返回才能按您的意愿工作:

var creditCheck = function(income)
{
    var val = income;
    return val;
};

然后你实际上必须使用括号来执行该功能:

var myScore = 750;
if (creditCheck(myScore) > 100) {
     //dosomething
} 

答案 1 :(得分:0)

您的意外令牌在这里:

} else {
  ^

导致它成为意外令牌的错误在这里:

if (creditCheck > 100); {
                      ^

if语句后你有一个额外的分号。这使得您的if语句后跟一个以分号结尾的空语句。这使得if语句后面的括号形成一个代码块,它本身是有效的。代码块出现后else本身无效。


如果您希望代码有意义,那么您应该在函数内部使用if语句,并在条件中使用参数而不是函数名称:

var creditCheck = function(income) {
  if (income > 100) { 
    return "You earn a lot of money! You qualify for a credit card.";
  } else {
    return "Alas, you do not qualify for a credit card. Capitalism is cruel like that.";
  }
};

答案 2 :(得分:0)

不确定这是否是您要做的事情:

var creditCheck = function (income) {
    var val = income;
    if (val > 100) {
        return "You earn a lot of money! You qualify for a credit card.";
    } else {
        return "Alas, you do not qualify for a credit card. Capitalism is cruel like that.";
    }
};