简体   繁体   中英

Javascript subarray that contains references to another array

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM