简体   繁体   中英

My Objects overwritten in array

I have a function that receives object each time it is called, I want to store this object in an Array. But when I push the arrived Object in the Array the previous Object is overwritten. How do I save the Objects without overwriting the previous ones each time am in the function, so that all the objects are printed in the for() function.

 drawtimeline(i_items, nom_cal, _hitoService, idcalbuscador) {
    var container = document.getElementById('timeLine');
     var result: any[] = [];
      result.push({  "_id": this.idcalbuscador, "title": nom_cal });
     for (let i of result) {
   console.log(i); 
         alert(i);
    }
}

Your result variable is local to the drawtimeline function. When that function finishes executing, the result variable is cleared. When that function is called again, a new result array is allocated, which makes it look like you are clearing the old object stored in the array. Each time you run the function you're printing a separate array containing the single object you just pushed.

The solution is to pull the result variable out of the function and into the outer scope. The details will depend on if this function is part of a module, a class, or bare. Typically it will look like this:

var result: any[] = [];
drawtimeline(i_items, nom_cal, _hitoService, idcalbuscador) {
    var container = document.getElementById('timeLine');

    result.push({  "_id": this.idcalbuscador, "title": nom_cal });
    for (let i of result) {
        console.log(i); 
        alert(i);
    }
}

If you are in a class, you will need to use this.result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM