我正在制作自动售货机但js错误:NaN

时间:2016-07-30 12:16:44

标签: javascript

`var y = 0 ;
var x = 0;
function atm(num1, num2){
console.log((num1 - num2));
return num1 - num2 ;
}
var items =[1,2,3,4,5,6,7,8,9,10];
function vm(y, x){
if( atm(y , items[x]) < 0  ){
    result = "U Do not have enough money to pay";
}
else if ( atm(y , items[x]) === 0  );{
    result = "Ur money just matches the required paying fee";
}
if ( atm(y , items[x]) > 0  );{
    result="U will reserve atm(y, items[x]) as a remainder";
}
}

vm(2, 3);`

**错误是它给了我3个答案,你可以看到: \\ -2

&#34; U没有足够的钱支付&#34;

&#34;你的钱只需支付所需的费用&#34;

-2

&#34; U将保留atm(y,items [x])作为余数&#34; \\

\\ 也是第3个结果&#34; result =&#34; U将保留atm(y,items [x])作为余数&#34; &#34;不会显示剩余部分

&#34; y支付你持有的金额&#34;

&#34; x转到数组&#34;

中的项目数

vm是自动售货机,它应该做的是显示这些的答案

1-你没有足够的钱支付

2- Ur钱只需支付所需的费用

3-是他有更多钱,他会保留&#34; y - items [x]&#34;作为剩余部分

当你收到我的错误时请写下错误和完整代码,有时候我会变得很难,我还是新的......

3 个答案:

答案 0 :(得分:1)

首先,您不会从函数atm返回任何内容,其次使用1参数而不是2来调用它,因此减法结果为NaN

例如,您只需使用1个参数

即可调用它
if (atm(y - items[x]) > 0) ...  

由于我不知道您的代码应该做什么,我无法为您解决,但我认为您应该能够在理解代码问题后做到这一点

答案 1 :(得分:1)

你的if语句中的

改变这个:

if( atm(y - items[x]) < 0  ){ ... }
else if ( atm(y - items[x]) === 0  );{ ... }
if ( atm(y - items[x]) > 0  );{ ... }

到此:

if( atm(y , items[x]) < 0  ){ ... }
else if ( atm(y , items[x]) == 0  ){ ... }
if ( atm(y , items[x]) > 0  ){ ... }

和此:

function atm(num1, num2){
    console.log(num1 - num2);
}

到此:

function atm(num1, num2){
    return (num1 - num2);
}

最终代码:

var y = 0 ;
var x = 0;
function atm(num1, num2){
        return (num1 - num2);
    }

var items =[1,2,3,4,5,6,7,8,9,10];
function vm(y, x){
if( atm(y , items[x]) < 0  ){
    result = "U Do not have enough money to pay";
}
else if ( atm(y , items[x]) === 0  ){
    result = "Ur money just matches the required paying fee";
}
if ( atm(y , items[x]) > 0  ){
    result="U will reserve atm(y, items[x]) as a remainder";
}
}

答案 2 :(得分:1)

2个错误:

  1. function atm(num1, num2)最终应为return

  2. atm(y , items[x]) < 0代替atm(y - items[x]) < 0

  3. 正确代码:

    &#13;
    &#13;
    var y = 0 ;
    var x = 0;
    function atm(num1, num2){
        console.log((num1 - num2));
        return num1 - num2
    }
    var items =[1,2,3,4,5,6,7,8,9,10]//Array.from({length:10},(v,k)=>k+1);
    function vm(y, x){
        if( atm(y , items[x]) < 0  ){
            console.log('U Do not have enough money to pay');
        }
        else if ( atm(y , items[x]) === 0  );{
            console.log("Ur money just matches the required paying fee");
        }
        if ( atm(y , items[x]) > 0  );{
            console.log("U will reserve atm(y, items[x]) as a remainder");
        }
    }
    vm(2, 1);
    &#13;
    &#13;
    &#13;