We help IT Professionals succeed at work.

Can you reference an object with a variable name?

MP techtrek
MP techtrek asked
on
If a variable contains a string that is the same as the name of an object. Can you use that variable in place of the object name?

https://cit111byui.github.io/object.html

Line 58 inside of the showInfo function:

carInfo.textContent = carSelected.getInfo();

Does not work as it is referencing the variable carSelect, but if I replace it with car0 or any of the objects it works fine. But the idea is to show the info of the car that is clicked on.

How can I get this to work?
Comment
Watch Question

Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019
Commented:
use :
carInfo.textContent = window[target.id].getInfo();

if you had a namespace/context for example "myapp" you had use :
carInfo.textContent = myapp[target.id].getInfo();

by default window is the context

Capture-d-e-cran-2020-03-18-a--04.48.png

Author

Commented:
Awesome, thanks leakim971