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

89
Visualizações
Logging array returns number when it's not suppose to

Basically I wanted the data from JSON to be accessible outside of the xml function as I have multiple functions I want to use it for.

So when I first tried it out and tried logging it, it did show the arrays with the objects in it. But when I did the same but checked the length instead it came out as zero. I looked this up and found out that it happens because both functions are running synchronously. So I looked into promises and implemented it like this:

let allTasks = []

// Read data
const dataPromise = new Promise((resolve, reject)=>{
    const xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status ==200) {
            const myData = JSON.parse(this.responseText)
            allTasks = allTasks.push.apply(allTasks, myData)
            resolve()
        }
    }
    xhttp.open("GET", "data.json", true);
    xhttp.send();
})
    
dataPromise.then(()=>{
    dataUse()
})

// Show data
dataUse = () =>{
    console.log(allTasks)
    // All variables
    const todos = document.querySelector('.todo')
    const todoInput = document.getElementById('new-todo')
    const added = document.getElementById('added')
    const itemsLeft = document.querySelector('.items-left > span')
    
    allTasks.forEach((datas)=>{
        const todo = document.createElement('div')
        todos.appendChild(todo)
        
        const input = document.createElement('input')
        input.setAttribute('type', 'checkbox')
        input.setAttribute('id', datas.name)
        input.setAttribute('class', 'checks')
        todo.appendChild(input)
        
        const label = document.createElement('label')
        label.setAttribute('for', datas.name)
        label.setAttribute('class', `${datas.name} tasks`)
        todo.appendChild(label)
        
        const span = document.createElement('span')
        label.appendChild(span)
        
        const paragraph = document.createElement('p')
        paragraph.innerHTML = datas.todo
        label.appendChild(paragraph)
    })
}

But now logging it gives me a number rather than the array with the objects, hence the function won't be able to do what it is suppose to.

So how do I fix this?

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

0

The problem is that you don't have to assign the return value of a push operation to the variable because the return value is the length of the array. Just push into the array and the variable will have the latest content.

Instead of allTasks = allTasks.push.apply(allTasks, myData), do allTasks.push(allTasks, myData).

It'll be good if you use const in place of let.

const allTasks = [];
allTasks.push(allTasks, myData);
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