Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda