簡體   English   中英

無法更改數組Javascript中的對象值

[英]can't change object value in an array Javascript

我在JS中有一個這樣的課程:

function configurationToken(){


this.setData= function(data){
    this.data=data;
};

this.configurationState=[];

this.analyse= function(){

#first loop to get an array called this.configurationState


#second loop to update this.configurationState 
#and put each updated state in array called trail.
for(var i=0;...;..){ 
this.configurationState[i].parameterValue = some number related to i 
this.PSTrail.push(this.configurationState);
}

#results in the final array
console.log(this.PSTrail);
}

}

問題是this.PSTrail數組中的對象都是SAME,這意味着在第二個循環中,代碼在不更改parameterValue的情況下推送了“ this.configurationState”,有人知道為什么嗎? 謝謝!

this.PSTrail.push(this.configurationState); 正在推送對該對象的引用,因此console.log將一遍又一遍顯示同一對象的數組。 如果希望PSTrail的每個條目包含不同的對象,則需要為每個推送創建一個副本。 我建議使用傳播語法: this.PSTrail.push({...this.configurationState});

如果您不熟悉該技術,那么這是在推送一個新對象( {} ),該對象包含與this.configurationState...this.configurationState )相同的所有內容。

 ref = [] copy = [] obj = {} for(var i=0;i<4;i++){ obj[i] = i; ref.push(obj) copy.push({...obj}) } console.log('ref result:',ref) console.log('copy result:',copy) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM