2017-04-03 108 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不存在。