2015-07-19 73 views
0

我想使用特定函數的返回值作爲if語句的條件。那可能嗎 ?使用函數返回作爲條件語句的內容

我基本上建立一個函數內的一個字符串,該函數接受一個數組(conditionArray)並將它連接到一個語句。 然後它以字符串的形式返回這個條件。 之後,我想用這個字符串作爲我的if語句的條件。

我目前的問題看起來像這樣。

var answer = prompt("Tell me the name of a typical domestic animal"); 
 

 
var conditionArray = new Array("Dog", "Turtle", "Cat", "Mouse") 
 

 
function getCondition(conditionArray) { 
 

 
    for (i = 0; i < conditionArray.length; i++) { 
 

 
    if (i != conditionArray.length) { 
 

 
     condition += 'answer === ' + conditionArray[i] + ' || '; 
 

 
    } else { 
 

 
     condition += 'answer === ' + conditionArray[i]; 
 

 
    } 
 

 
    return condition; 
 

 

 
    } 
 

 
} 
 

 
if (getCondition(conditionArray)) { 
 

 
    alert("That is correct !"); 
 

 
} else { 
 

 
    alert("That is not a domestic animal !"); 
 

 
}

+0

一件事是你'if'聲明您使用的是賦值運算符(=)而不是等號(==)。 –

回答

0

對於這種類型的測試使用Array.prototype.indexOf的,x = arr.indexOf(item)

  • x === -1裝置item不在arr
  • 否則xarr索引中的第一次出現item位於
var options = ["Dog", "Turtle", "Cat", "Mouse"], 
    answer = prompt("Tell me the name of a typical domestic animal"); 

// some transformation of `answer` here, i.e. casing etc 

if (options.indexOf(answer) !== -1) { 
    alert("That is correct !"); 
} else { 
    alert("That is not a domestic animal !"); 
} 
+0

感謝您的幫助。它應該解決我目前的問題。但對於未來和更多問題。如上所述,是否有機會在條件語句中寫入字符串? – theCodingPeanut

0

做這種測試的最好方法是使用Array.prototype.indexOf。有關如何使用它的更多細節,請參閱Paul的答案。

-

如果你真的真的想返回的條件,你可以使用eval()評估條件的字符串。請記住,eval()是危險的,但。這是使用不建議。見https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Don%27t_use_eval_needlessly!

if (eval(getCondition(conditionArray))) { 
    alert("That is correct !"); 
} else { 
    alert("That is not a domestic animal !"); 
} 
+0

感謝您的詳細解釋,這就是我正在尋找。儘管如此,你是對的,它對於生產來說太危險了:/ – theCodingPeanut

+0

要清楚,除非你自己編寫解析器,否則沒有其他方法可以評估條件字符串。你可以做的一件事是在將字符串傳遞給eval函數之前進行消毒。 –