我有一个函数,然后是一个if else语句,然后在其中返回数学值

时间:2018-12-02 01:20:50

标签: javascript html

// var
var differentBillsInUSD;

// start of bills
differentBillsInUSD = {
    firstBill: parseInt(124),
    secondBill: parseInt(48),
    thirdBill: parseInt(268),
    fourthBill: parseInt(180),
    fifthBill: parseInt(42),
}

// console to check if everything is alright
console.log(differentBillsInUSD);
console.log("Checking if bill is alright ^");

function calcBill(numberBill) {
    if (numberBill < 50) {
        return(numberBill + " tip is: " (numberBill*0.20));
    } else if (numberBill >= 50 && numberBill <= 200) {
        return(numberBill + " tip + total is: " (numberBill*0.15));
    } else if (numberBill > 200) {
        return(numberBill + " tip + total is: " (numberBill*0.20));
    }
}
function calcBillTotal(numberBill) {
    if (numberBill < 50) {
        return(numberBill + " tip + total is: " ((numberBill*0.20)+numberBill));
    } else if (numberBill >= 50 && numberBill <= 200) {
        return(numberBill + " tip + total is: " ((numberBill*0.15)+numberBill));
    } else if (numberBill > 200) {
        return(numberBill + " tip + total is: " ((numberBill*0.20)+numberBill));
    }
}

// first bill
console.log(calcBill(differentBillsInUSD.firstBill));
console.log(calcBillTotal(differentBillsInUSD.firstBill));

// second bill
cosnole.log(calcBill(differentBillsInUSD.secondBill));
cosnole.log(calcBillTotal(differentBillsInUSD.secondBill));
ERROR CODE
script.js:21 Uncaught TypeError: " tip + total is: " is not a function
    at calcBill (script.js:21)
    at script.js:37

它不起作用,因为我正在应对编码挑战。 看来我是javascript新手。 我试图做我的研究,很难找到。 我在代码中间,但是无法修复。

3 个答案:

答案 0 :(得分:0)

return(numberBill +“提示是:” + (numberBill * 0.20));

您只是想在其中加一个加号...

答案 1 :(得分:0)

return(numberBill +“提示+总计为:”(numberBill * 0.15));

在JS中,如果您将()放在任何后面,它将尝试将其作为函数执行。因为您错过了“(numberBill * 0.15)”前面的“ +”,所以它试图执行“ tip + total is:”作为函数。您只需要添加一个“ +”

答案 2 :(得分:0)

将字符串与变量连接时,需要在JavaScript中使用“ +”号。在这里,如果您在每个if,else if和else语句中都注意到您缺少“ +”号。

if(numberBill <50){         return(numberBill +“提示是:” + (numberBill * 0.20));