Console.log返回错误的答案

时间:2014-12-17 02:56:39

标签: javascript

我是JS的新手,这是我的第一个逻辑编程语言。出于某种原因,无论我的收入和loanAmount是什么,都会返回console.log。什么不能显示“已批准”消息?

function LoanApp(personName, income, loanAmount){
    this.personName = personName;
    this.income = income;
    this.loanAmount = loanAmount;

    var bankBranch = "New York";
    var approvalStatus = "invalid";

    this.submit = function (income, loanAmount){
        if (income / loanAmount >= 2) {
            approvalStatus = "Approved";
            console.log("Congrats you're approved for " + this.loanAmount + ".")
        } else {
            approvalStatus = "On Review";
            console.log("Your application needs further review.")
        };
    };
};

var tony = new LoanApp("Tony"5000,1000);
tony.submit();  //returns else console.log but should be "Congrats"

2 个答案:

答案 0 :(得分:3)

您的submit函数定义为function (income, loanAmount)。由于您未向函数传递任何内容,因此两者都设置为未定义,undefined / undefined >= 2评估为false

要解决这个问题,你需要做的就是:

  1. 从函数声明中删除参数。

  2. 在函数中将所有income替换为this.income(与loanAmount相同),因此它知道要查找它们的范围。

答案 1 :(得分:0)

您所要做的就是将关键字this附加到if then语句中的变量,以确定值是否为> = 2.这将使函数可以访问变量,否则无法访问它们,因为它们不在函数范围内。

Javascript:jsfiddle example - http://jsfiddle.net/larryjoelane/zrkdyq9c/6/

function LoanApp(personName, income, loanAmount){
    this.personName = personName;
    this.income = income;
    this.loanAmount = loanAmount;

    var bankBranch = "New York";
    var approvalStatus = "invalid";

    this.submit = function (income, loanAmount){
        if ((this.income / this.loanAmount) >= 2) {  //<-----change that fixes code



            approvalStatus = "Approved";
            console.log("Congrats you're approved for " + this.loanAmount + ".")
        } else {


            approvalStatus = "On Review";
            console.log("Your application needs further review.")
        };
    };
};

var tony = new LoanApp("Tony",5000,1000);
tony.submit();  //returns else console.log but should be "Congrats"