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

179
Vistas
Javascript array.push does not seem to work in a for loop

I have come across very strange behavior in nodeJS. I am trying to initialize an empty array and then fill that array inside a for loop. See the simplified code below.

let arr = []
for (let i = 0; i < 20; i++) {
    console.log(arr)
    arr.push(`hello`)
}
console.log(arr)

This outputs just an empty array at every instance of the loop and afterwards.

[]
[]
[]
[]
...
[]

I can't for the life of me figure out why that is. I assume it has something to do with scoping but the array is still accessible inside the loop when I do a straight assignment to it. Any help would be greatly appreciated!

Edit: Here is the full code that I am struggling with. The arr.push does not seem to push the new urls into the arr. Thank you

const getRandImgs = async (ct) => {
    console.log('At the top of getRandImgs')
    try {
        let arr = []
        if (ct > 30) {
            arr = await getRandImgs(30)
            console.log(arr)
            ct -= 30
        }

        const config = {
            params: {
                collections: '483251',
                count: ct
            },
            headers: {
                Authorization: 'Client-ID XXXXXXX'
            }
        }
        const res = await axios.get('https://api.unsplash.com/photos/random', config)

        for (const d of res.data) {
            console.log(d.urls.full)
            console.log(arr)
            arr.push[d.urls.full]
            console.log(arr)
        }
        return arr
    } catch (e) {
        console.log(e)
    }
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your line

arr.push[d.urls.full]

should be

arr.push(d.urls.full)
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