user3013562
user3013562

Reputation: 29

array changing values for a strange reason

Given the code below:

function createJson() {
var varry = new Array();
varry = x;
for (i=0 ; i < arry.length ; i++) { 
    if (arry[i]["questionVisibility"] == "1"){
        if (arry[i]["questionType"] != 3) {
            varry[i][1] = document.getElementById('te'+arry[i]["id"]+'et').value;
        } else {
            e = document.getElementsByName("te"+arry[i]["id"]+"et")[0];
            p = e.options[e.selectedIndex];
            varry[i][1] = p.text;
        }
    }
}

console.log(x);
console.log(varry);

Where X is an array that has been created like this(inside a different function):

x = document.getElementById("jsonData").value;
x = JSON.parse(x);
x = x[0];
x = x.data;
x = JSON.parse(x);

Can anyone explain me why when i call the createJson() function, the x array is changed? (x is already created when the createJson() is called) Thanks in advance!

Upvotes: 0

Views: 67

Answers (1)

bestestefan
bestestefan

Reputation: 871

it's because of line

varry = x;

assigning an array to variable creates kind of reference of original value so when you modify varry it also modifies x

if you want to get a copy of x into varry without reference use array.slice() like this:

varry = x.slice();

this will insert values from x into varry without creating 'reference' to original array

Upvotes: 3

Related Questions