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?
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.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.