2014-04-07 38 views
1

讓我更詳細地解釋一下,我正在爲我的數學老師製作一個小圖,用於計算三角形的缺失邊和角度。我有if/else/else if語句,但是我想要一個else if語句,如果其他語句都不爲真,它將輸出類似「檢查拼寫」的內容。基本上,我想要的東西,會做這樣的事情(記住,我不知道如何編程,但本)將多個參數添加到else if語句中?

// More code above 
else if (side != "hypotenuse and adjacent"; "hypotenuse and opposite"; "opposite and adjacent") { 
    confirm("Please check spelling."); 
} 

你能看到什麼,我試圖做的?前一個變量稱爲「側」,它會提示用戶輸入三角形的哪一側,因此草圖可以計算出角度。如果他們有拼寫錯誤,並且它與我設置的任何參數不匹配,如果它們不匹配,我將如何使它跟隨此代碼塊?我可能只是在這裏過於複雜的事情,但如果有人能告訴我如何做到這一點,那將是極大的讚賞

回答

1

您可以嘗試indexOf

possibilities = ["hypotenuse and adjacent", "hypotenuse and opposite", "opposite and adjacent"] 

// so if side not in that array (the same as not in any of that values) 
if (possibilities.indexOf(side) == -1) {} 
+0

*插件組的'標準免責聲明:原型:在IE8及以下* –

0

你問了,如果沒有一個默認的聲明其他人是否匹配?這不就是一個正常的其他陳述嗎? else{//what you want here}

0

我能想到的最簡單的方法是使用ifelse ifelse。通過最後使用else,您不需要爲自上一行以來的最後一行寫一個巨大的檢查。

if (A) { A is true } else if (B) { Not A, but B } else if (C) { Not A or B, but C } else { Not A, B or C }

一個更漂亮的方式做到這招,就是用一個switch/case,被描述here

switch(n) { case A: A is true break; case B: B is true break; default: Not A or B }

但是,如果你只想要「拼寫檢查」最後一次檢查,我會說@zishe有着簡潔的答案。

+0

雖然正確indexOf'·需要polyfilled,這是矯枉過正。 –

0

最簡單的方法來做到這一點是使用jQuery功能:

$.inArray(value, array) 

如果字符串可以陣列或否則爲-1的內部可以找到它返回任一正折射率。因此,解決方案應該是這樣的:

var myArray = ["hypotenuse and adjacent", "hypotenuse and opposite", "opposite and adjacent"]; 

// more code above 
else if($.inarray(side, myArray) == -1) { 
    confirm("Please check spelling."); 
}