I have four variables and I want to change their values using a function where I just can put in an array storing the variables. I'm making a game which uses a coordinate system and therefore I have four coordinates that I want to constantly update with y-axis and x-axis. I have one array, yAxis, with all y values and one array, xAxis, with all x values. I want to combine them into the coordinates. Of course, I can update them using the following code:
yAxis = [10, 10, 9, 9];
xAxis = [4, 4, 5, 5];
coordinate1 = "" + yAxis[0] + xAxis[0];
coordinate2 = "" + yAxis[1] + xAxis[1];
coordinate3 = "" + yAxis[2] + xAxis[2];
coordinate4 = "" + yAxis[3] + xAxis[3];
But instead of changing their values like earlier I would like to do something like this: This function will take the array below, coordinatesArray as a, yAxis as b, and xAxis as c. Then x is just an integer.
test(a, b, c){
for(x = 0; x < 4; x++){
a[x] = "" + b[x] + c[x];
}
}
and then I would call this function like this:
coordinatesArray = [coordinate1, coordinate2, coordinate3, coordinate4];
test(coordinatesArray, yAxis, xAxis);
What it then should do with whatever array I run the test function with:
coordinatesArray[0] = "" + yAxis[0] + xAxis[0];
coordinatesArray[1] = "" + yAxis[1] + xAxis[1];
coordinatesArray[2] = "" + yAxis[2] + xAxis[2];
coordinatesArray[3] = "" + yAxis[3] + xAxis[3];
And for example coordinatesArray[0]
should then represent coordinate1
.
So I would create an array to store the variables so I can easily change which variable to target. The problem though, when I run this, a[x] isn't the variable name, instead, it is their values which means this doesn't work. So my question is, is there any way to store the variables' names in an array so I can target them using a function similar to the one I showed? I want to store the names of the variables in an array and then be able to use the name to target the variable so I can change their values.