tags:

views:

66

answers:

1

How to I achieve the following functionality?

I have an array:

a = [1, 2, 3, 4, 5]
b = [a[1], a[2], a[3]] //This array should be some kind of "array of references"

Any change in the array b should be applied to array a, as well.

+7  A: 

The problem is that primitive values (String, Number, Boolean, undefined and null), work by value, and they are non-mutable.

If you use objects as the array elements you can get the desired behavior:

var a = [{value: 1}, {value:2}, {value:3}, {num:4}];
var b = [a[1], a[2], a[3]];

alert(a[1].value); // 2
b[0].value = "foo";
alert(a[1].value); // "foo"
CMS
Interesting idea +1
Daniel Vassallo
Nice trick... Hopefully it will solve my problem. Any ideas how this affects overall performance?
markovuksanovic
@markovuksanovic, I don't think you will have any performance issues, `b` is simply an *array of references*, the values of each array element are just references pointing to the original objects. Just be careful to not create circular references, that would cause the object to never be garbage collected. @Daniel, thanks!
CMS