2017-04-03 109 views
0

我有一个功能,必须采取不同的行为,如果pan.cost > 0否则如果语句被忽略

所以我们说curPos = 3pan.cost = -1

现在我这样做的时候,不管是什么,if(curPos + 1 === 5 || 30)始终使用,即使curPos + 1是2,3,4,6等(只要pan.cost < 0

现在我已将console.log(curPos + 1)放在else if-statement之内,并且还表示它不符合要求。

function action(curPos) 
{ 
    var pan = panel[curPos]; 

    if(pan.cost > 0) 
    { 

    } 
    else if(curPos + 1 === 5 || 39) 
    { 
    console.log(curPos + 1); 

    } 
    else if(curPos + 1 === 3) 
    { 
    console.log("should be here"); 

    } 
} 
+5

方面的问题是'如果(CURPOS + 1 === 5 || 39)',你需要'如果((CURPOS + 1)=== 5 ||(CURPOS + 1)=== 39)' – Satpal

+0

没有人认为这很奇怪,他将“pan”设置为一个数字,然后将下一行视为对象? – Slime

+0

@Waxi对不起,对象被声明在其他地方。但我认为这对于这个问题并不是相关的 –

回答

1

试试这个:

function action(curPos) 
{ 
    var pan = panel[curPos]; 
    var newCurPos = (curPost + 1); 

    if(pan.cost > 0) 
    { 

    } 
    else if(newCurPos === 5 || newCurPos === 39) 
    { 
    console.log(newCurPos); 

    } 
    else if(newCurPos === 3) 
    { 
    console.log("should be here"); 

    } 
} 
+0

谢谢!接受你的回答(在5分钟内),因为你是第一个。但所有其他答案也很棒! –

+0

太棒了。很高兴帮助。 –

1

线

curPos + 1 === 5 || 39

始终计算为truthy,因为它是阅读:

(curPos + 1 === 5) || 39

39是truthy值。

1

if(curPos + 1 === 5 || 39)将始终评估为真。看看你或管道后面的部分。 if(39)将始终为真。

1

|| 39将始终返回true,并且pan.cost不存在。