开发者

Is is possible for one variable to point to another?

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

var theArray = [0,1,2开发者_如何学C,3];
var secondElement = //somehow point to theArray[1]

so that if I modify theArray[1], secondElement should also be modified and vice versa (possibly, without using functions)?


There's no way to do that directly. The array could be an array of objects, and you could modify properties of the objects instead of the array entries directly. Then you would have:

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

then changes to theArray[1].value would also be visible in secondElement.value.

I would offer the observation that functions are friendly things and they won't hurt you if you don't try and pick them up by the tail.


You can use object properties and wrap your array with an 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);


You're asking about references -- for primitive values, it's not directly possible in Javascript. It is 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>

In the above example, the object b has a property refToA which contains the object a; both reference the same actual object, so changes to the object b.refToA and a are reflected through both ways of accessing it. This reference is broken if you reassign either b.refToA or a. Similarly with arrays:

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] and b[1] both have a value that is the same reference to an object.

The effect you're looking for can only be achieved if the shared object is a mutable container, so that your two desired variables have (and always have) the same value, which is a reference to the shared mutable container. You can change values in the container, and they will be seen by both means of access. Primitive values (e.g. numbers and strings) are not mutable containers so they can't be used this way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜