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

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

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