1

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?

Sébastien
  • 11,860
  • 11
  • 58
  • 78
Someone
  • 121
  • 1
  • 7
  • 2
    can you share an example of how this might be used in your software? – tatmanblue Dec 21 '17 at 20:16
  • 1
    No... it's a primitive value. – Andrew Li Dec 21 '17 at 20:16
  • What do you mean by "*wherever x is*"? Do you need to lookup the index of the "replaced value" dynamically? Is the "previous" value guaranteed to be in the array? Is the array guaranteed to never contain duplicates? – Bergi Dec 21 '17 at 20:23
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures – ibrahim mahrir Dec 21 '17 at 20:24
  • It's kind of wack. I'm using four-dimensional arrays as sprite sheets in a canvas game, and I want to have a simple way to change key elements the sprites' animations without having to write different setter functions for every sprite. – Someone Dec 21 '17 at 20:41

2 Answers2

4

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.

Sébastien
  • 11,860
  • 11
  • 58
  • 78
4

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);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375