cube
cube

Reputation: 1802

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)

Upvotes: 0

Views: 84

Answers (3)

ug_
ug_

Reputation: 11440

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,3)
//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.
}

Upvotes: 2

bren
bren

Reputation: 4334

If you have an array of things and want to check if it has something, I would use the new .includes() property on arrays:

["Sun", "Mon", "Tue", "Wed", "Thu"].includes(today);

Also, instead of extracting the day of the week from the string output, use Date.prototype.getDay().


If you don't want to include the polyfill, you can use this trick I learned from Codegolf.SE:

~["Sun", "Mon", "Tue", "Wed", "Thu"].indexOf(today);

The ~ is a binary NOT operator, which will transform the bits in a data type to their opposite. The binary NOT of -1, which is returned from .indexOf() when there are no instances of the search term, is 0. In JavaScript there's a concept called coercion, which means that when there's typal dissonance, like adding booleans, for example, there are values of one type that will convert to another. For example, all numbers that are not zero are coerced to true, and 0 coerces to false. Becuase of this, if you put the above text into an if statement, it will act as if it is an .includes().


A better way

You're extracting the day of the week from the Date.toString(), which is not good practice. Consider using array access and Date.prototype.getDay() to make the process a lot more logical:

let today = new Date().getDay();
//   Sun., Mon., Tue., etc.
if ([true, true, true, true, true, false, false][today]) {
  // Day is matched

} else {
  // Day is not matched
}

This has some advantages

  1. Ultimate Customizability. You can specify exactly which days you want to match
  2. Doesn't rely on strings. Your method of extracting from the string is going to get tripped up in non-English user agents, becuase their Date Strings will be different.

Upvotes: 0

madox2
madox2

Reputation: 51851

Your loop continue looping when isDay becomes true and in the next iterations could assign false to it. You could use break statement to exit loop:

var isDay = false;
for (var daysChosen of ['Sun','Mon','Tue','Wed','Thu'])
{
    if (today == daysChosen) {
        isDay = true;
        break;
    }
}

You can also use Array.prototype.find() function to check if array contains today. (!! is double negation):

var isDay = !!['Sun','Mon','Tue','Wed','Thu'].find(function(day) {
    return day === today;           
})

Unfortunately find is not compatible with all browsers.

Upvotes: 2

Related Questions