Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery variable values bleeding

i am totally missing something here. I need to define a base variable. Then reference that base varialbe in a series of second variables. Each of the second variables will be provided alternate values. However I am seeing the modified values bleed back to the base variablle

for example

<script>
var a = [{a:1}];
var b = a;
b.a = 22;
alert('a-a equals' + a.a + ' and b-a equals ' + b.a);
</script>

I want a.a to equal 1 and b.a to equal 22. however I am seeing both equal 22. Can someone explain what I am missing?

like image 300
jeff werner Avatar asked Feb 04 '26 18:02

jeff werner


2 Answers

You are missing the fact that var b = a; doesn't create a new copy of a into b, it actually assigns the reference of the object stored in a into b. What this means is that any actions you take against the object stored in b is happening to the object stored in a at the same time. That is because in reality they are the EXACT SAME object!

a and b are really just telling the code where it can find the underlying object in memory, and in this case they are both pointing to the same place.

like image 117
mclark1129 Avatar answered Feb 07 '26 10:02

mclark1129


var b = a; this will just copy the reference to the actual array (The array will not be copied)

You can copy your array like this -

var a1 = [{a:1}];
var a2 = JSON.parse(JSON.stringify(a1));
a2[0].a = 22;
console.log('a-a equals' + a1[0].a + ' and b-a equals ' + a2[0].a);

Or -

var a2 = $.map(a1, function (obj) {
    return $.extend({}, obj);
});

Demo --> http://jsfiddle.net/vTpSk/

like image 26
Mohammad Adil Avatar answered Feb 07 '26 11:02

Mohammad Adil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!