Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

angular - Typescript Array of Objects not Storing as expected

If you looked a the console results, I have no idea as to why the array of objects is now 235 235 on both indexes, it should be 234 235.Am I doing a passing or pushing of values wrongly to the array? A little confused by the typescript syntax here.

Firstly I have a object class.

export class MassDelete {
   constructor (
      public slotId?: string
   ){
      }
}

In my component class.

studentsForDelete : Array<any> = [];
massDeleteList: Array<MassDelete> = [];

massDel = new MassDelete();


   onDel(){

    if(this.delAction == 'DEL'){
      this.delAction = '';//Reset it
      console.log("student for deletion");

      for(let i = 0; i < this.studentForDelete.length; i++){
        console.log("what is i " + i);
        console.log(this.studentForDelete[i].slotId);

        this.massDel.slotId = this.studentForDelete[i].slotId;
        console.log("What is mass Del slot ID?");
        console.log(this.massDel.slotId);

        this.massDeleteList.push(this.massDel);
        


        console.log("massdel test");
        console.log(this.massDeleteList);

      }

      console.log("list for del");
      console.log(this.massDeleteList);




    }
    this.router.navigate(["/confirm"]);
  }


in the console.log

What is i 0
What is mass Del Timeslot ID?
234
massdel test
[t]
0: t?{Id: "234"}
     {slotId : "234"}
    length: 2
    __proto__: Array(0)


what is i 1
What is mass Del Timeslot ID?
235
massdel test
(2) [t,t]
0: t?{slotId: "235"}
     {slotId : "235"}
    length 2
    _proto_: Array(0)

list for del
(2) [t,t]
0: t?{slotId: "235"}
     {slotId : "235"}
    length 2
    _proto_: Array(0)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This isn't specific to TypeScript. Objects in JavaScript are accessed by reference. So, when you add an object to an array, you add a reference to that object. The object itself is not cloned.

So, for example, by doing this:

let obj = new MassDelete();
array.push(obj);
array.push(obj);

You're pushing the same object twice. Which means than modifications to either also appear on the other one, because, well, they're the same object.

You should probably create a new object each time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...