简体   繁体   中英

I have a problem while running the below code, I want to print msg

I am trying to run the code but the error like "Object error comes"

 var today= new Date(); var hourNow = today.getHours(); if (hourNow > 18) { console.log("GoodEvening"); } else if (hourNow > 12) { console.log("GoodAfternoon"); } else if (hourNow > 0) { console.log("GoodMorning"); }

try below code

index.html

<html>
  <head>
    <title>My awesome webpage</title>
  </head>
  <body>
    <h1>This site is awesome!</h1>
    <p>And I coded it from scratch.</p>
    <div id="disply-date"></div>
    <script>
      var today= new Date(); 
      var hourNow = today.getHours(); 

      if (hourNow > 18) { 
        console.log("GoodEvening");
        document.getElementById("disply-date").innerHTML = "GoodEvening";
      }
      else if (hourNow > 12) { 
        console.log("GoodAfternoon"); 
        document.getElementById("disply-date").innerHTML = "GoodAfternoon";
      }
      else if (hourNow > 0) {
        console.log("GoodMorning");
        document.getElementById("disply-date").innerHTML = "GoodMorning";
      }
    </scirpt>
  </body>
</html>

 console.log(["Good Morning", "Good Afternoon", "Good Evening"][~~(new Date().getHours() / 8)]);

Code Golf!

How this works:

You don't need to create a new Date object and stash it in a variable if you are just getting the hours. So you can do: new Date().getHours() .

It also turns out, that you can place your messages in an Array and select the message you want like: var arr = ["Good Morning", "Good Afternoon", "Good Evening"]; console.log(arr[2]); var arr = ["Good Morning", "Good Afternoon", "Good Evening"]; console.log(arr[2]); . But you don't need to stash the array in a variable to get the message. You can do this: ["Good Morning", "Good Afternoon", "Good Evening"][2] . Sure, it looks a little weird, but it's saying, "Hey, here's an array of strings, get me the one at index 2."

So how to get the hours and turn it into 0, 1 or 2 (our indexes)? Well, take the hours and divide by 8. That will get you close. Say it's 7:30 am. You take 7 / 8 and get 0.875. That isn't an index. We need to round down. So we can do Math.floor(7/8) and we get 0.

We can feed THAT ( 0 ) to our array and get Good Morning . Cool. Math.floor is too many characters to type and I'm lazy. There's a Javascript hack using bitwise operators explained here . Basically ~~ does a Math.floor . So we can cheat and do ~~(new Date().getHours() / 8) to turn the hours into 0 , 1 , or 2 .

Take that result, get our string out of our array and smash the entire thing into console.log.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM