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?

5
  • 2
    can you share an example of how this might be used in your software? Commented Dec 21, 2017 at 20:16
  • 1
    No... it's a primitive value. Commented Dec 21, 2017 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? Commented Dec 21, 2017 at 20:23
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures Commented Dec 21, 2017 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. Commented Dec 21, 2017 at 20:41

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.