【问题标题】:Typescript Array of Objects not Storing as expectedTypescript 对象数组未按预期存储
【发布时间】:2021-01-06 03:32:29
【问题描述】:

如果您查看控制台结果,我不知道为什么对象数组现在在两个索引上都是 235 235,它应该是 234 235。我是否错误地将值传递或推送到数组?这里的打字稿语法有点困惑。

首先我有一个对象类。

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

在我的组件类中。

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"]);
  }


在控制台日志中

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)

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    这并不特定于 TypeScript。 JavaScript 中的对象是通过引用来访问的。因此,当您将对象添加到数组时,您添加了对该对象的引用。对象本身没有被克隆。

    因此,例如,通过这样做:

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

    您将同一个对象推了两次。这意味着对其中任何一个的修改也会出现在另一个上,因为它们是同一个对象。

    您可能应该每次都创建一个新对象。

    【讨论】:

    • 好的,我明白了!它就像一个指向同一个对象的指针。我可以在同一个帖子上问更多问题吗?还是我必须重新发布一个新帖子!它与此有关,但与其他问题有关
    • 你应该问一个不同的问题。 Stack Overflow 不是论坛:接受我的回答意味着您已经解决了这个问题,其他问题需要其他问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    • 2016-10-08
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多