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.

1 Answer 1

7

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"
Sign up to request clarification or add additional context in comments.

2 Comments

Nice trick... Hopefully it will solve my problem. Any ideas how this affects overall performance?
@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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.