So I am trying to return a number for what week day it is given a string like 'tue'
.
So i figured I would get the index of the string 'tue'
in an array that contains the week days
week_days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
var date = new Date();
var first_month_day = String(new Date(date.getFullYear(), date.getMonth(), 1).toString().slice(0, 4).toLowerCase());
var indexOf = week_days.indexOf(first_month_day)
return indexOf;
first_month_day
= 'tue'
as of today when I evaluate that code.
therfore I would assume that running
week_day.indexOf(first_month_day)
would return 2
but instead i get -1
. So if instead of running the above if i do
week_days.indexOf('tue')
I get the desired 2
I have ensured that first_month_day is a string using typeof
and everything I am just at a loss as to why it keeps returning -1
whenever I know it exists inside the array.
CodePudding user response:
As Robin Zigmond said, .slice(0, 4) will give a string with a length of 4, so you were getting "tue " from firstMonthDay instead of "tue".
const weekDays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
const date = new Date();
const firstMonthDay = String(new Date(date.getFullYear(), date.getMonth(), 1).toString().slice(0, 3).toLowerCase());
const index = weekDays.indexOf(firstMonthDay);
console.log(index);