【问题标题】:If else, more variables for same output (JS) [duplicate]如果否则,相同输出(JS)的更多变量[重复]
【发布时间】:2018-05-04 12:30:25
【问题描述】:

我正在尝试为同一输出“数学书”添加多个值。我想我缺少一些关于如何格式化括号中的值的基本知识。

<script type="text/javascript">
  <!--
  var book = "maths";
  if (book == "history") {
    document.write("<b>History Book</b>");

    /*How to add more options below besides "maths" so the output will be "Maths
    Book". I want the output to be "Maths Book" also when user enters 
    mathemathics, mata, maths book...

    Do I need more else if lines or I can put additional values in in brackets*/


  } else if (book == "maths") {
    document.write("<b>Maths Book</b>");
  } else {
    document.write("<b>Unknown Book</b>");
  }
  //-->
</script>
<p>Set the variable to different value and then try...</p>

【问题讨论】:

  • 您正在寻找logical OR operator,但如果您当前的资源足以推荐&lt;!-- … //--&gt;,您还应该找到学习JavaScript 的更新资源。
  • 你的意思是if (book.toLowerCase().indexOf("math") !=-1)
  • 我正在使用 tutorialspoint.com PDF JS 教程。 &lt;!-- … //--&gt; 有什么问题

标签: javascript


【解决方案1】:

尝试以下脚本和 JSFiddle:https://jsfiddle.net/19d7g8f0/2/ 会有所帮助

function addBook(book){
   if( book == "history" || book=="archive"){
      document.write("<b>History Book</b>");
   }else if( -1 != ["maths","mathematics","arithmetics"].indexOf(book.toLowerCase()) ){
      document.write("<b>Maths Book</b>");
   }else{
      document.write("<b>Unknown Book</b>");
   }
}

addBook("Maths");
addBook("mathematics");
addBook("Arithmetics");

【讨论】:

  • 我正在尝试做一些更简单的事情:在 else if ( book == "math", "matemathica") 中添加更多选项,以便每个值都输出为 Maths Book。所以我不必添加更多行。如何正确格式化?
  • 啊...尝试 else if ( book == "math" || book == "matemathica")
  • 是的!而已!非常感谢。我不知道我每次都需要再次输入book==。没有book==有没有更简单的方法?
  • 您可以尝试 .... else if( -1 != ["maths", "mathematics","arithmetics"].indexOf(book.toLowerCase()) ) 忽略大小写比较
  • 我已经改变了我的答案然后匹配:)干杯!
猜你喜欢
  • 2012-12-09
  • 2022-08-13
  • 2018-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-28
  • 1970-01-01
相关资源
最近更新 更多