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

102
Visualizações
JavaScript for loop string to array

It just all of a suddenly crossed my mind we all know using regular for loop and push() method to convert string characters into an array

let myStr = "Perseverance";
let emptyArr = [];

for (let i = 0; i < myStr.length; i++) {
    emptyArr.push(myStr[i]);
}
console.log(emptyArr); 

then I decided to convert a whole string into a single element of an array just using push()...worked

let myStr = "Perseverance powers";
let emptyArr = [];

for (let i = 0; i < myStr.split().length; i++) {
  emptyArr.push(myStr);
}
console.log(emptyArr);

Now here when I want to separate each word into a single element of an array just using push() I can't... Here is my question: How can I convert each word of the string into a single element of an array using only push() and for loop

P.S. A lot ways exist yet it was just a thought came to my mind 'what if' Thanks

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

0

You can use JavaScript's split to create an array of words.

const myStr = "Perseverance powers";
const arr = myStr.split(' ');
console.log(arr);

documentation for split

Here's what I came up with if you want to do this using push

const str = 'Perseverance powers';
const arr = [];
let temp = '';

str.split('').forEach(character => {
    if(character === ' ') {
    arr.push(temp);
    temp = '';
  } else {
    temp += character;
  }
})
arr.push(temp);

console.log(arr)

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