Someone
Someone

Reputation: 121

Reference Array Elements in JavaScript

Let's say I have the following code in JavaScript:

var x = 2;
var myArray = [0,1,x];
x = 3;

Changing the value of x would leave myArray completely unchanged, so myArray[2] would still be 2.

How could I set it up so that I can change the element at myArray[*wherever x is*] repeatedly without actually knowing the index?

Upvotes: 1

Views: 49

Answers (2)

Bergi
Bergi

Reputation: 664444

You could define a getter that acts as a reference to the live variable:

var myArray = Object.defineProperty([0,1], 2, {
    get() { return x },
    enumerable: true,
    configurable: true
});
var x = 2;
console.log(myArray);
x = 3;
console.log(myArray);

Of course, this is a horrible thing to do to an array, and will probably incur heavy performance penalties in every place where the array is used. So: don't do this. Just assign to myArray[2] instead of x in every place, or use a getter/setter function pair instead of the x variable that does this.

function setX(v) { myArray[2] = v; }
var myArray = [0,1,2];
setX(2);
console.log(myArray);
setX(3);
console.log(myArray);

Upvotes: 4

Sébastien
Sébastien

Reputation: 12139

You could put your value in an object.

var x = {
  value: 2
}
var myArray = [0,1,x];
console.log(myArray[2].value); // 2

x.value = 3;
console.log(myArray[2].value); // 3

In this case you are always pointing to the same object, the content of which can change at any time.

Upvotes: 4

Related Questions