cube cube - 3 months ago 10
Javascript Question

Iterating the days of the week

I have this piece of code which iterates a chosen set of days and should ring

true
if today is part of the chosen set. However,
isDay
rings
false
regardless of the
daysChosen
or what
today
happens to be. So what am I missing here?..

var date = new Date;
var isDay;
var today=date.toString().substring(0,4)
//console.log(today)//good
for (var daysChosen of ['Sun','Mon','Tue','Wed','Thu'])
{
console.log(daysChosen)//good
isDay = today==daysChosen ? true : false
}
console.log(isDay)//bad, should be true if today is part of daysChosen


Update:
Ok, this is some BULL ****!!!... how on earth can this evaluate to true given that
today
is in the array!?...

for (var value of ['Sun','Mon','Tue','Wed','Thu','Fri'])
{
var _day = (today!=value) ? true : false
break;
}
console.log(_day)

ug_ ug_
Answer

You have a few major problems that are causing you issues in your code.

  1. var today=date.toString().substring(0,4) - The days are 3 characters long, so your getting the extra space at the end. today === "Sun ", notice the extra space.

  2. Your not breaking out of your loops once you find the correct value as other answers have pointed out.


You can simply use the indexOf method. It returns the index of the given string or -1 if its not contained in the array.

var date = new Date();
// first 3 characters from string for day of week
var today = date.toString().substring(0,3);
var days = ['Sun','Mon','Tue','Wed','Thu'];

var isInDays = days.indexOf(today) > 0; // indexOf returns -1 if not contained

Or to fix your existing code:

var date = new Date;
var isDay;
var today=date.toString().substring(0,4)
//console.log(today)//good
for (var daysChosen of ['Sun','Mon','Tue','Wed','Thu'])
{
    console.log(daysChosen)//good
    isDay = today==daysChosen ? true : false
    if(isDay) break; // must break once you find it or you will keep overriding the value.
}