变量更改其他变量更改

时间:2018-07-09 21:55:30

标签: angular typescript angular5

我为两个不同的自变量分配了一个源变量,但是如果我更改了第一个变量,则第二个变量也会更改。

  list: Array<any> = [];
  savedList: Array<any> = [];

 constructor() { }

 ngOnInit() {
   this.sharedService.list.subscribe(response => {
   console.log('Component--List---', response);
   if (response) {
    this.list= response
    this.savedList= response
   }
  });
 }

onEvent(event){
  console.log('this.list---1---',this.list,'this.savedList',this.savedList);
  this.list.push(event.item.source);
  console.log('this.list---2---',this.list,'this.savedList',this.savedList);

}

为清晰起见,打印了控制台日志:

Component--List--- (1)[{…}]
this.list---before---(1) [{…}] this.savedList (1)[{…}]
this.list---after--- (2) [{…}, {…}] this.savedList (2) [{…}, {…}]

2 个答案:

答案 0 :(得分:2)

这是因为您的两个变量是对原始响应对象的引用。试试:

if (response) {
    this.list= Object.assign({}, response);
    this.savedList= Object.assign({}, response);
   }

答案 1 :(得分:0)

这符合我的预期

vkFlushMappedMemoryRanges()