Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

142
Vistas
Array.indexOf() return confusing results JavaScript

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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda