无法弄清楚这个简单的JS代码有什么问题

时间:2015-07-30 17:35:30

标签: javascript

标题是自我解释我有这个JS代码(回到基础)非常简单,但我不能为我的生活弄清楚为什么我不会跑。我所知道的是开发者控制台说出了意想不到的令牌" {"在第21行,但那是打开我的if语句的原因。

enter code here
<!Doctype html>
<html land="en">
   <head>
       <meta charset="utf-8" />
      <title>Chapter 2, Example 7</title>
   </head>
   <body>
       <script type="text/javascript">
         var myAge = parseInt(prompt ("Enter your age", 30),10);

         if (myAge >= 0 && myAge <= 100) {
            document.write("myAge is between 0 and 10<br />");
         }
         if (!(myAge >= 0 && myAge <= 10) ) {
            document.write("myAge is NOT between 0 and 10<br />");
         }
         if (myAge >= 80 || myAge <= 10) {
            document.write("myAge is 80 or above OR 10 or below<br />");
         }

         if ( (myAge >= 30 && myAge <= 39 || (myAge >= 80 && myAge <= 89) ) {
            document.write("myAge is between 30 and 39 or myAge is " +
            "is between 80 and 89");
        }
        </script>
      </body>
   </html> 

2 个答案:

答案 0 :(得分:2)

你错过了这一行的括号

if ((myAge >= 30 && myAge <= 39 || (myAge >= 80 && myAge <= 89)) {

应该是

if ((myAge >= 30 && myAge <= 39) || (myAge >= 80 && myAge <= 89)) {

答案 1 :(得分:0)

变化

if ( (myAge >= 30 && myAge <= 39 || (myAge >= 80 && myAge <= 89) ) {

if ( (myAge >= 30 && myAge <= 39) || (myAge >= 80 && myAge <= 89) ) {

或者如果您愿意,可以使用关键字operator precedence

if (myAge >= 30 && myAge <= 39 || myAge >= 80 && myAge <= 89) {

并略微提示

if (myAge >= 0 && myAge <= 100) { // <-- or this should be 10 ...?
    document.write("myAge is between 0 and 10<br />");
} //                                       ^^
//                               should be 100?