Home > database >  Problems with multidimensional arrays in Typescript and Angular
Problems with multidimensional arrays in Typescript and Angular

Time:10-21

I have this code to fill a multidimensional array

filaCalendario: string[] = [];
filasCalendario: string[][] = [];

crearFila(){
for (let actividad of this.listaActividades) {
  this.filaCalendario.push(actividad.faseId);
  this.filaCalendario.push(actividad.descripcion);
  for (let dia of this.cabeceraCalendarioNumeroDiaDeLaQuincena) {
    if (new Date(actividad.fecha).getDate() == dia) {
      this.filaCalendario.push(actividad.duracion.toString());
    }
    else {
      this.filaCalendario.push("");
    }
  }

   this.filasCalendario.push(this.filaCalendario);

   this.filaCalendario.splice(0);
  }
  console.log(this.filasCalendario);
 }
}

After push filaCalendario into filasCalendario I delete the elements of filaCalendario to push the new values but after

this.filasCalendario.push(this.filaCalendario);

this.filasCalendario is empty too

After push it the first time i get this

enter image description here

And after splice filaCalendario I get this

enter image description here

Any idea, please?

Thanks

CodePudding user response:

Your problem is this: When you do a someArray.push(x) operation you are not creating a new string and adding that to the array. You are adding a reference to that string.

So when you do

this.filaCalendario.splice(0);

You are truncating the filaCalendario array. The reference to that array will also reflect the truncated array. Try:

this.filaCalendario = []; 

instead. That will allocate a new array in memory and leave the reference to the prior array untouched.

  • Related