0

I'm running a psychology experiment in js. I have an array of strings and I'm replacing the text in two of these strings.The array changes depending on the input I want from my participants. So I have the original array Array1, which contains some placeholder values, and a duplicate array that contains the values I want participants to see Array2. I enter the new values using .replace. Weirdly (or maybe it's just my understanding of js), using Array2[n].replace('placeholder', 'new text') replaces the placeholder in both arrays. Here's some script that replicates the issue (in Chrome).

Array1 = ['rhubarb', 'placeholder', 'rhubarb', 'rhubarb']
Array2 = Array1
Array2[1] = Array2[1].replace('placeholder', 'new text')

Array1

["rhubarb", "new text", "rhubarb", "rhubarb"]

Using Array2 = Array1.slice() eliminates the issue, so I guess Array2 = Array1 is only pointing to Array1 rather than copying it. Why does Array2 = Array1 allow modifications to Array2 to travel up the chain of reference, so to speak?

I'm sure this is fairly basic, but I'm not a programmer. Thanks in advance!

ivan.k
  • 15
  • 2

2 Answers2

1

Your problem is actually, that two arrays are pointing to the same data; I mean they do not contain separate values. In order to copy values of an old array, you have better use .slice method. It looks like this

Array2 = Array1.slice() Array2[1] = Array2[1].replace('placeholder', 'new text');

0

An array in javascript is also an object. Objects are treated as references. Basically they point to the same piece of data. The logical consequence is that if you modify one, it affects the other.

If you want to create a clone (independent copy) to avoid this kind of behavior you might want to refer to this question on how to duplicate arrays. It has plenty of answers.

Community
  • 1
  • 1
Blizz
  • 8,082
  • 2
  • 33
  • 53