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