Is it possible for one variable to point to another?

Is it possible for one variable to point to another in such an array,

var theArray = [0,1,2,3];
var secondElement = //somehow point to theArray[1]

so if I change theArray[1], secondElementshould it also be changed and vice versa (perhaps without using functions)?

+3
source share
3 answers

You ask for links - for primitive values, this is not directly possible in Javascript. Possible w / r / t objects:

C:\WINDOWS>jsdb
js>a = []
js>b = {refToA: a}
[object Object]
js>b.refToA.push(3)
1
js>a
3
js>a.push(4)
2
js>b.refToA
3,4
js>

b refToA, a; , b.refToA a . , b.refToA, a. :

js>x = {y: 3, toString: function() { return 'y='+this.y; }}
y=3
js>a = [x]
y=3
js>b = [3,x]
3,y=3
js>a[0].y = 22
22
js>b
3,y=22
js>b[1].y = 45
45
js>a
y=45

a[0] b[1] , .

, , , , ( ) , . , . (, ) , .

+2

. , . :

var theArray = [ { value: 0 }, { value: 1 }, { value: 2 }, { value: 3 } ];
var secondElement = theArray[1];

theArray[1].value secondElement.value.

, - , , .

+3

You can use the properties of the object and wrap the array with the object:

var a = {arr: [1,2,3,4]};
var b = a;
b.arr[0] = 777;
console.log(a.arr);

This method has the advantage that you can also assign new values ​​to both a.arr, and b.arr.

var a = {arr: [1,2,3,4]};
var b = a;
a.arr = [777,888];
console.log(b.arr);
+3
source

Source: https://habr.com/ru/post/1786688/


All Articles