简体   繁体   中英

Having trouble with variable reference in javascript

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM