-2

Suppose I have a few variables:

a = 1
b = 2
c = 3
d = 4
vars = ['a', 'b', 'c', 'd'] // Values of them stored in a list

Now, I have a for loop:

for (i = 0; i < vars.length; i ++){
    console.log(vars[i]);
}

Here, the output would be a,b,c,d but what I'm willing to get is 1,2,3,4.

Note: The vars list should remain the same. This is just an example of what I'm trying to do...

Any idea on how we could fetch the variable just by a string name (given that the string name is exactly the same as the variable name)?

11
  • 1
    Duplicate Get global variable dynamically by name string in JavaScript Commented Oct 21, 2022 at 13:14
  • 6
    What problem would this solve for you? Commented Oct 21, 2022 at 13:14
  • 1
    Also your variables should be declared with let, const, or (if really necessary) var. Commented Oct 21, 2022 at 13:14
  • 2
    Also, see "Variable" variables in JavaScript. In practice, you never need — or want, really — dynamic variable names. Use a simple object instead: const obj = { a: 1, b: 2, c: 3, d: 4 };console.log(obj[vars[i]]);. Commented Oct 21, 2022 at 13:23
  • I simply stated a normal example and I am aware of variable declaration. I don't want the list to be changed simply. Commented Oct 21, 2022 at 13:26

1 Answer 1

0

I am assuming you're working in a browser.

Since a, b, c, and d are global variables, you can get them from the window object:

a = 1
b = 2
c = 3
d = 4
vars = ['a', 'b', 'c', 'd'] // Values of them stored in a list

for (i = 0; i < vars.length; i ++){
    console.log(window[vars[i]]);
}

Sign up to request clarification or add additional context in comments.

1 Comment

Assuming a browser environment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.