-1

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.

Nik Hendricks
  • 244
  • 2
  • 6
  • 29
  • Consider debugging issues first - `first_month_day` is `'undefined'` – CertainPerformance Feb 12 '22 at 23:24
  • `.slice(0, 4)` will always give a string of length 4 (assuming the pre-sliced string has length at least 4), so it can't be `tue`. Did you mean `.slice(0, 3)`? – Robin Zigmond Feb 12 '22 at 23:26
  • [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) and [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173) – VLAZ Feb 13 '22 at 07:33

1 Answers1

1

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);
mstephen19
  • 1,733
  • 1
  • 5
  • 20