-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)?

The Myth
  • 1,090
  • 1
  • 4
  • 16
  • 1
    Duplicate [Get global variable dynamically by name string in JavaScript](https://stackoverflow.com/questions/1920867/get-global-variable-dynamically-by-name-string-in-javascript) – esqew Oct 21 '22 at 13:14
  • 6
    What problem would this solve for you? – Pointy Oct 21 '22 at 13:14
  • 1
    Also your variables should be **declared** with `let`, `const`, or (if really necessary) `var`. – Pointy Oct 21 '22 at 13:14
  • 2
    Also, see ["Variable" variables in JavaScript](/q/5187530/4642212). 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]]);`. – Sebastian Simon Oct 21 '22 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. – The Myth Oct 21 '22 at 13:26
  • @Pointy I would like to fetch the user page and based upon that I have variables which I would like to run in a function (without if conditions). – The Myth Oct 21 '22 at 13:27
  • The idiomatic JavaScript approach would be to have an object contain properties, which can be accessed by a name that's computed somehow, like `object["a"]`. – Pointy Oct 21 '22 at 13:45
  • @Pointy it won't work in my case since I'll also end up with `undefined` or null strings. – The Myth Oct 22 '22 at 10:53
  • Well how would you expect things to work with `undefined` or `null` strings if you were gaining access to plain variables somehow? – Pointy Oct 22 '22 at 11:04
  • That's why I added a one-timer if condition. – The Myth Oct 22 '22 at 11:19
  • I was trying to fetch the page user is on for animation purposes, I've done it now :) – The Myth Oct 22 '22 at 11:19

1 Answers1

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]]);
}
Matt Ellen
  • 11,268
  • 4
  • 68
  • 90