user5715447
user5715447

Reputation:

Why is for loop modifying an additional variable not referenced in the line (Javascript)?

I set two global variables:

var topList = {
    a: {},
    b: {},
    c: {},
    d: {},
    e: {}
}

var compare = {
    a: {},
    b: {},
    c: {},
    d: {},
    e: {}
}

I have a function which populates each of them, and then uses a for loop to swap out the a object within the compare variable. Then it calls a function to compare the new compare to topList, and returns the better of the two (thus setting topList as the better of the two:

function optimize(data){

    var rawList = data.slice();

    var aList = $.grep(rawList, function(e) { return e.position == "A" });
    var bList = $.grep(rawList, function(e) { return e.position == "B" });
    var cList = $.grep(rawList, function(e) { return e.position == "C" });
    var dList = $.grep(rawList, function(e) { return e.position == "D" });
    var eList = $.grep(rawList, function(e) { return e.position == "E" });

    topList.a = aList[0];
    topList.b = bList[0];
    topList.c = cList[0];
    topList.d = dList[0];
    topList.e = eList[0];

    compare = topList;

    for (i = 0, len = aList.length; i < len; i++) {
        compare.a = aList[i];
        topList = best(topList, compare);
    }
}

For some reason, it seems that when the line compare.a = aList[i]; is executed, it's not only swapping out the a object in the compare variable, but also the a object in the topList variable. As a result I'm always sending two identical lists through my "best" function, which makes it useless.

I'm new to this. Any help would be greatly appreciated!

Upvotes: 3

Views: 62

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324750

In an attempt to explain simply, when you do:

var x = {};

You take an empty object and assign it to x.

If you then do:

var y = x;

You are taking the same object and assigning it to y as well.

From then, if you do...

y.foo = 'bar';

You will find that...

alert(x.foo); // bar (!)

This is called assignment by-reference, and it is what happens in JavaScript with objects (note that arrays are objects too, with predefined methods).

The opposite is assignment by-value, where the value is copied to the new variable.

So because you have this by-reference assignment, changes you make in one place will affect the other. You will need to use a copying function to get a new object, unrelated to the first, with the same value.

Upvotes: 3

ikken
ikken

Reputation: 563

Because compare is a reference to topList. You don't need to put

compare =topList;

Simply, this would work :

compare .a = aList[0];
compare .b = bList[0];
compare .c = cList[0];
compare .d = dList[0];
compare .e = eList[0];

Upvotes: 0

Related Questions