Reputation: 555
I'm trying to derive 4 points on a grid from an original point. These include left, right, bottom and top by one unit.
If I start out with [4, 5]
my output should be [3, 5] [5, 5] [4, 4] [4, 6]
.
I could probably look up how to do this but instead I've been playing with my own method, and I think my logic is sound, yet I'm having a simple issue with JavaScript itself where when I declare var tempArr = cords;
, from thereon out, any changes to tempArr
appear to be affecting cords
. I've never had this problem before, here is the code.
var output = [],
cords = [4, 5];
var convertToCords = function(i){
var tempArr = cords;
var offset = ( ( i%2 ) * 2 ) - 1, // -1, 1, -1, 1
index = Math.floor(i/2); // 0, 0, 1, 1
tempArr[index] = cords[index] + offset;
return tempArr;
}
for (var i = 0; i < 4; ++i){
console.log(cords);
newCords = convertToCords(i);
var x = newCords[0],
y = newCords[1];
array[i] = "[" + x + ", " + y + "]";
}
console.log(output);
tempArr[index] = cords[index] + offset;
The question: Can anybody spot why when I do something to tempArr
, cords
is affected too? Should I be declaring tempArr
in another manner?
See the jsFiddle
Upvotes: 0
Views: 52
Reputation: 298196
var tempArr = cords;
is your problem. cords
and tempArr
refer to the same array object, even though the variable names are different. You need to make a clone of your original array:
var tempArr = cords.slice(0);
Upvotes: 2