Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays 'glued' at initialization

I've found a kind of estrange effect while I was using several related arrays. After break my mind looking for the error, finally I've found a solution. But I would like to know if any of you can explain me why is happening this.

My code was something like:

var closed =['closed', 'closed', ..., 'closed'];
sunday = closed;
...
saturday = closed;

After this if i do:

sunday[2] = 'open';

I get sunday[2] = 'open', monday[2] = 'open', tuesday[2] = 'open', ..., saturday[2] = 'open'. It's like all the variables were been 'glued' or linked because no mater which you change, all of them change in the same way.

I've fixed it in this way:

var closed1 =['closed', 'closed', ..., 'closed'];
...
var closed7 =['closed', 'closed', ..., 'closed'];
sunday = closed1;
...
saturday = closed7;

And now I get independent variables. But I don't like this solution, so I'd be grateful if someone knows the problem. I'm running JavaScript over Google Chrome.

Thanks

like image 514
Oscar Parra Avatar asked Dec 09 '25 15:12

Oscar Parra


2 Answers

Arrays are Objects, and Objects are reference types.

Each variable sunday, monday, tuesday, etc... holds a reference to the same Array, so each variable is able to observe changes to that Array.


Looking at your code, I have a gut feeling that maybe you should be using an Object instead of an Array.

var closed = {
    sunday:    'closed',
    monday:    'open',
    tuesday:   'open',
    wednesday: 'open',
    thursday:  'open',
    friday:    'open',
    saturday:  'closed'
};

Just a hunch though. Thought I'd throw it out there.

like image 86
I Hate Lazy Avatar answered Dec 12 '25 05:12

I Hate Lazy


The problem is that in JavaScript, object types (which includes arrays like closed in your example) are references to the actual object (related question). This means that if x is a variable and its value is of object type, y = x does not put a copy of x into y; it simply means that you can use both names to refer to the same object.

What you would actually want here is to create copies of closed ("clone" it). Since it's an array, you can easily do that with

sunday = closed.slice(0); // etc
like image 35
Jon Avatar answered Dec 12 '25 07:12

Jon



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!