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

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

0

Your line

arr.push[d.urls.full]

should be

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