0

I've added a button to call this function

onPress(){
    if(!this.data) this.data = this.test;
    else for(var i in this.test) this.data.push(this.test[i]);
    console.log(this.test.length);
}

On the first call this.test is assigned to this.data. I suppose it is passed by value not by reference. So when the iteration change the value of this.data, it will not affect this.test.

But I am wrong. this.test's value is changed. I know the workaround is I should avoid to assign it directly. Define this.data = [] in constructor first. And iteration is the only way. But is it supposed to work that way or am I missing something?

stackunderflow
  • 1,492
  • 1
  • 23
  • 53

2 Answers2

2

Arrays and Objects are always passed by reference. Only primitive types are passed by value.

You could make a copy of the object by stringify to JSON and parse again:

this.data = JSON.parse(JSON.stringify(this.test));
Alexander Kuttig
  • 426
  • 3
  • 10
2

Yes, you are wrong. Arrays in JavaScript are stored by reference consider the code below

a = []
b = a
b.push(1)
console.log(a) //will logout [1]

If you want to create a new copy of the array you can do something like

a =[1, 3, ]
b = [...a]
b.push(4)
console.log(a)
console.log(b)
// This logs a as [1,3] and b as [1, 3, 4]

However, if the first array has some value that is stored by reference, for example, an array or an object that value will as well be modified if its modified in B i.e

a = [ [2], [4]]
b = [...a]
b[0].push(5)
console.log(a) // logs out a as [[2,5], 4]

One simple solution to solve that will be using JSON.stringify and JSON.parse i.e

a = [ [2], [4]]
b = JSON.parse(JSON.stringify(a))
b[0].push(5)
console.log(a) 
console.log(b)
// logs out a as [ [2], [4]] and b as [[2,5], 4]

However, if the data you are working with is too much JSON.stringify and JSON.parse become expensive operations and you might want to look at something like immutablejs or look at an alternative to create deep copies of such data structures. Hope this helps

Jjagwe Dennis
  • 1,643
  • 9
  • 13