当前位置: 代码迷 >> JavaScript >> 使用函数return作为条件语句的内容
  详细解决方案

使用函数return作为条件语句的内容

热度:94   发布时间:2023-06-13 12:36:29.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 !"); } 

对于此类测试,请使用 , x = arr.indexOf(item)

  • x === -1表示item不在arr
  • 否则, x是第一个出现的itemarr索引
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 !");
}

进行这种测试的最佳方法是使用 。 有关如何使用它的更多详细信息,请参见Paul的答案。

-

如果你真的 真的想返回一个状态,你可以使用eval()来计算条件的字符串。 请记住,尽管eval()很危险。 不建议使用它。 请参见

if (eval(getCondition(conditionArray))) {
  alert("That is correct !");
} else {
  alert("That is not a domestic animal !");
}
  相关解决方案