Home > Mobile >  javascript array push giving different length
javascript array push giving different length

Time:01-01

I am getting weird length value when using array push in javascript code in angular environment

userData:any[]=[];

loadData():any[]{
    this.userData.push({name:"name1",email:"email1"});
    this.userData.push({name:"name2",email:"email2"});
    console.log("! " this.userData.length);
  return this.userData;
  }

loadData is called from its corresponding component.html file:

<p>one works!</p>
<u *ngFor="let user of loadData()">
    <li>{{user.name}}</li>
</u>

enter image description here

I was expecting output to be 2. Is there a kind of lifecycle happening here?

Also when I replace the loadData function with following, everything works fine. Length comes out to be 2. Like this:

 loadData():any[]{
  //   this.userData.push({name:"name1",email:"email1"});
  //   this.userData.push({name:"name2",email:"email2"});
  //   console.log("! " this.userData.length);
  // return this.userData;
  let userData2 = [{name:"name1",email:"email1"},{name:"name2",email:"email2"}];
  console.log(userData2.length);
return userData2;  
}

I crossed checked without angular, and push method is giving me array length as 2 there. I am confused with this ngFor behavior with push method.

CodePudding user response:

Your function is currently pushing 2 additional objects into your array every time you call loadData()

loadData()
console.log(this.userData.length) // 2

loadData()
console.log(this.userData.length) // 4

loadData()
console.log(this.userData.length) // 6

If you want to initialise some test data in an array by running a function, in order to be able to reuse this function, make sure you are either:

  • Assigning the data to your variable (instead of calling .push())
loadData(): any[] {
  this.userData = [
    {
      name: "name1",
      email: "email1"
    },
    {
      name: "name2",
      email: "email2"
    }
  ]
}

loadData()
console.log(this.userData.length) // 2

loadData()
console.log(this.userData.length) // 2
  • If you want to use .push(), make sure you reset your variable before pushing
loadData(): any[] {
  this.userData = [];
  this.userData.push({
    name: "name1",
    email: "email1"
  });
  this.userData.push({
    name: "name2",
    email: "email2"
  });
}

loadData()
console.log(this.userData.length) // 2

loadData()
console.log(this.userData.length) // 2
  • Related