问题描述
我想将特定函数的返回值用作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 !"); }
1楼
对于此类测试,请使用 , x = arr.indexOf(item)
-
x === -1
表示item
不在arr
-
否则,
x
是第一个出现的item
的arr
索引
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 !");
}
2楼
进行这种测试的最佳方法是使用 。 有关如何使用它的更多详细信息,请参见Paul的答案。
-
如果你真的 真的想返回一个状态,你可以使用eval()
来计算条件的字符串。
请记住,尽管eval()
很危险。
不建议使用它。
请参见
if (eval(getCondition(conditionArray))) {
alert("That is correct !");
} else {
alert("That is not a domestic animal !");
}