Home > Software engineering >  Extreme bizarre behavior on simple function
Extreme bizarre behavior on simple function

Time:09-22

i am normally simply trying to update a value on input bu i am encountering an extreme bizarre behavior i cannot really explain nor fix.

updatePriceAndDuration(amount: number) {
if(amount < 1) amount = 1;
this.activeViewElement.elementTime = this.funcList[this.clickedObject].elementTime * amount;

if(this.activeViewElement.costResources[901]) {
  this.activeViewElement.costResources[901] = this.funcList[this.clickedObject].costResources[901] * amount;
}
if(this.activeViewElement.costResources[902]) {
  this.activeViewElement.costResources[902] = this.funcList[this.clickedObject].costResources[902] * amount;
}
if(this.activeViewElement.costResources[903]) {
  this.activeViewElement.costResources[903] = this.funcList[this.clickedObject].costResources[903] * amount;
}

}

This is the update function, the problem is that somehow the variable funcList which contains the base values will also get updated but i really do not understand why.

So for example: The first funcList element has the value 2.000 for costResources.903 but after the first entry (for example the amount of 2) it becomes 4.000 and so on and the calculation of course becomes wrong. Am i not updating the activeViewElement variable on this and not the funcList variable? I am so confused as i really never experienced such a case in a few years of coding.

CodePudding user response:

It looks like somewhere in Your code this.activeViewElement and this.funcList are bound by reference. Simplest way to check it will be to create deep copy of this.funcList before it's value is assigned to this.activeViewElement. If it'll fix the issue it will mean that you have bounded references, it's hard to say without looking at the rest of the code but it'll be my guess.

  • Related