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!