views:

80

answers:

3

I have an array of objects with various objects within to hold UI values. I wanted to have a button so that element 0's values are replicated through the whole array. However I noticed that setting one set them all. Here is an example without using any looping:

console.log('manual 3: ', lis[3].spacer.divider.type); // prints 'none'
lis[1].spacer.divider.type = 'bananas';
console.log('manual 3: ', lis[3].spacer.divider.type); // prints 'bananas'

I am completely baffled how setting lis[1] also set lis[3]

A: 

They must both be references to the same object.

If they're DOM nodes, you can copy them using cloneNode(). Watch out for IE bugs - it has a habit of not cloning properly (for example cloning a <select> doesn't maintain the selectedIndex).

See also What is the most efficent way to clone a JavaScript object? for cloning objects.

Greg
A: 

Because the variables are reference variables and they all reference the same object and as a result it looks like changing one changes all of them, really they are all the same underlying object.

If you want lots of unique arrays they should all be created as a fresh or be clones of each other.

Robert
A: 

Hey

It turns out I was referencing the same object. Thanks. It didn't click to me since all the other objects above (spacer,lis) were unique. I accidentally was setting divider to a member default of spacer instead of a function returning the default.

Thanks!

Shawazi