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);