0

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

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

This seems counter intuitive, any insight into why it's this way? Your solution fixed the problem so I'll mark this answered, but I'm still baffled by this behavior. Using slice also seems like a workaround, are there others?
@Jamil: What makes you think it's unintuitive? As for .slice(), that's how you make a shallow clone of an array object.
Perhaps because I'm used to php where I would have to add & to get this behavior. Pretend you didn't have your experience and were newer to this like me. Can't you agree it's counter intuitive because you're adding operation to an object simply trying to make an exact clone? Either way thanks for the help!
@Jamil: I'd find it more counter-intuitive if the language decided to clone objects for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.