简体   繁体   English

splice 方法删除两个数组中的元素

[英]splice method deletes the elements in two arrays

I have the following error.我有以下错误。 When I use splice in 1 array, it deletes the element in both arrays.当我在 1 个数组中使用 splice 时,它​​会删除两个数组中的元素。 Code:代码:

export class AgendarpacientesComponent implements OnInit {
   arrayPrueba: number[]=[1,2,3,4,5]
}

constructor(){
  this.metodo();
}
ngOnInit() {}

metodo(){
  let arrayAux = this.arrayPrueba;
  arrayAux.splice(1,1);
  console.log(this.arrayPrueba);
}

the result of console log is: [1,3,4,5] and I've used the splice method only on arrayAux.控制台日志的结果是:[1,3,4,5] 并且我只在 arrayAux 上使用了 splice 方法。 I don't know why this is happening.我不知道为什么会这样。

Thanks for helping !感谢您的帮助!

You have two references to the same array.您有两个对同一个数组的引用。 Changes made to any reference, affect the same object.对任何引用所做的更改都会影响同一对象。 Use something like spread operator to make a copy :使用扩展运算符之类的东西来制作副本:

let arrayAux = [...this.arrayPrueba];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM