Jump to content

Translate 1 line of PHP to JS


paulmo

Recommended Posts

This was written by justsomeguy about 3 years ago and I need it in Javascript. Please just get me started so I can learn something. Like does JS have intval function and ternary statement?

$temp = (intval(date('G')) < 12) ? 'morning' : (intval(date('G')) < 18) ? 'afternoon' : 'evening';

And it needs to go in here, so I get "Sunday morning" etc:

<script type="text/javascript">var now = new Date();var dayNames = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");//var hourTime =new Array??document.write(dayNames[now.getDay()]);</script>

Thanks in advance.

Link to comment
Share on other sites

JavaScript has a ternary statement, yes. It also has an equivalent to intval(), called parseInt(), though I don't think you'll need it for this case. You can just use the corresponding method from the date object.

Link to comment
Share on other sites

But if you find it cooler, why not use it? Like I said, JavaScript does have a ternary statement... or did you simply now find it (like most people) less readable?

Link to comment
Share on other sites

You can always use brackets in the else... it's the same deal, like:

condition ? then : (condition ? then : else)

Link to comment
Share on other sites

I was just reading that ternary is slower than if/else...true? Anyhow here is my attempt. How close is it?

time<12 ? document.write(" morning, ") : (time>12 && time<18 ? document.write(" afternoon, ") : document.write(" evening, ");

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...