Unexpected changes in an object array using Node.js

0

I have the following problem with a code that I made (similar to what would be Open Hashing).

I have the following code in javascript:

let o = function(){
 this.a;

 this.geta=function(){return this.a;}

 this.seta=function(a){this.a=a;}
};

let i,j,l;
let a=[];
let p=[2,7,9,2,6];

let aux=new o();
aux.seta(p[0]);
a[0]=new Array(1);
a[0][0]=new o();
a[0][0]=aux;

console.log('Procesing ',p[0]);

for(i=1;i<p.length;i++){
  aux.seta(p[i])
  for(j=0;j<a.length;j++){
    if(a[j][0].geta()==aux.geta()){
      l=a[j].length;
      a[j][l]=new o();
      a[j][l]=aux;
    }
  }
  if(j==a.length){
    a[j]=new Array(1);
      a[j][0]=new o();
      a[j][0]=aux;
  }
  console.log('Procesing ',p[i]);
}
console.log('---------------------------------------------------------------------');
for(k=0;k<a.length;k++){
  for(n=0;n<a[k].length;n++){
    console.log('Value:',a[k][n].geta());
  }
  console.log('End of Bucket ',k);

}

When executing it, in the arrangement I find 4 buckets all with numbers 6 nothing else. When in reality should appear the 2,7,9.

Thank you very much;)

    
asked by Tuti Videla 08.11.2018 в 16:31
source

1 answer

1

Within the first cycle for you are assigning to the variable aux the i-th value of the fix p and then you save aux in the matrix a but you are not saving a new object, you are saving the same object again and again so that in the last iteration of the first cycle for saves in the aux variable the value of 6 and since all the values of the matrix are that aux object when printing them they show you that value, add a line of code to create a new object o for each iteration of the first cycle for

let o = function(){
 this.a;

 this.geta=function(){return this.a;}

 this.seta=function(a){this.a=a;}
};

let i,j,l;
let a=[];
let p=[2,7,9,2,6];

let aux=new o();
aux.seta(p[0]);
a[0]=new Array(1);
a[0][0]=new o();
a[0][0]=aux;

console.log('Procesing ',p[0]);

for(i=1;i<p.length;i++){
  aux = new o();
  aux.seta(p[i]);
  for(j=0;j<a.length;j++){
    if(a[j][0].geta()==aux.geta()){
      l=a[j].length;
      a[j][l]=new o();
      a[j][l]=aux;
    }
  }
  if(j==a.length){
    a[j]=new Array(1);
      a[j][0]=new o();
      a[j][0]=aux;
  }
  console.log('Procesing ',p[i]);
}
console.log('---------------------------------------------------------------------');
for(k=0;k<a.length;k++){
  for(n=0;n<a[k].length;n++){
    console.log('Value:',a[k][n].geta());
  }
  console.log('End of Bucket ',k);

}
    
answered by 08.11.2018 / 19:00
source