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

100
Vistas
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 Respuestas
Responde la pregunta

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