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

607
Visualizações
How can a string be iterated using a for of() method and a indexOf() method to find certain indexes and getting the expected results?

I'm trying to iterate a string, using a for of, in order to determine the indexes of the empty spaces that the string has, and log to console these indexes. I have a string that contains 4 white(or empty?) spaces, so using this for of method and making use of indexOf(), I'm expecting to see in console 4 different indexes numbers, however, the behavior is weird and it logs the index of the first white space found, for every white space found later. What could be causing this?

Here's a 'running snippet'.

const tipo = 'Quimes Bajo Cero  ';
    
    
for(char of tipo){
  char === ' ' ? console.log(tipo.indexOf(char)) : console.log('this character is not empty space');
}

Thank folks.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

That is because indexOf method returns the index of the first matching char in a string so in your case black's first match is at the 6th index. Read the Definition and Usage

about 4 years ago · Juan Pablo Isaza Relatório

0

you can use forEach, transform the string and loop

const tipo = 'Quimes Bajo Cero  ';
[...tipo].forEach((char, index) => char === ' ' ? console.log(index) : console.log('this character is not empty space')
)

about 4 years ago · Juan Pablo Isaza Relatório

0

Does it have to be implemented with "for...of" logic? The same can be done with the following logic as well:

for(let i=0;i<tipo.length;i++){
    if(tipo[i] === ' '){
        console.log(i);
    }
}
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