如果,否则如果不工作的JavaScript

时间:2015-08-21 05:44:07

标签: javascript jquery

我正在编写自己的JARVIS(有点像铁人一样) 但是else if语句不起作用

function ttalk(code) {
    varpo = code;
    if (varpo == "good morning") {
        var currentdate = new Date();
        var hours = currentdate.getHours();
        if (hours >= 12)  {
            dn=PM;
        } else {
            dn=AM;
        }
        varso = "Good Morning, Sir. The time now is "  + currentdate.getHours() + "  " + currentdate.getMinutes() + dn;
    } else if (varpo == "hello") {
        varso = "reading your F.B. Notifications.";
    } else {
        varso = "Not Got That, Sir";
    }

    speaker.speak("en", varso);
}

当我说Good Morning它确实说time now时,但每当我说hello它说Not Got That, Sir时,为什么?

带有输入字段的完整代码进行测试试试这个

Enter Text To Play:
<input id="text">&nbsp;(Recognized text for voice will also appear here)
<br><br>
<button class="btn btn-success" onclick="stalk()">Talk It!</button>
<button class="btn btn-success" onclick="listen()">Recognize My Voice</button>

<script>
    var speaker = new RobotSpeaker();
    var listener = new AudioListener();

function stalk() {
 var varpo = document.getElementById("text").value;
 if (varpo == "good morning") {
    var currentdate = new Date();
    var hours = currentdate.getHours();
          if (hours >= 12)  { dn=PM;} else {dn=AM;}
       varso = "Good Morning, Sir. The time now is "  + currentdate.getHours() + "  " + currentdate.getMinutes() + dn;
} 
else if (varpo == "hello") {
  varso = "reading your F.B. Notifications.";
}
else {
   varso = "Not Got That, Sir";
}
        speaker.speak("en", varso);
    }

2 个答案:

答案 0 :(得分:1)

我尝试了你的代码并且工作正常,你需要将PM和AM更改为&#34; PM&#34;和&#34; AM&#34;分别

当我用&#34;早上好&#34;

执行时,输出如下 先生,早上好。现在的时间是14 58PM

当你通过&#34;早安&#34;它显示如下。由于区分大小写。

没有,先生

答案 1 :(得分:0)

请尝试这个,使用javascript提供的内部字符串比较。

function ttalk(code) {
    varpo = code;
    if (varpo.localeCompare("good morning")==0) {
        var currentdate = new Date();
        var hours = currentdate.getHours();
        if (hours >= 12)  {
            dn=PM;
        } else {
            dn=AM;
        }
        varso = "Good Morning, Sir. The time now is "  + currentdate.getHours() + "  " + currentdate.getMinutes() + dn;
    } else if (varpo.localeCompare("hello")==0) {
        varso = "reading your F.B. Notifications.";
    } else {
        varso = "Not Got That, Sir";
    }

    speaker.speak("en", varso);
}

由于 阿米特