简体   繁体   中英

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!

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.

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

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