I’m trying get value of var by its name:
var1='Hello'
var2 = getTextFromFirstTextBox() //text in label is "var1"
var3 = ${var2}
Everything works, but here I should get ‘hello’ but it doesn’t work
var4 = ${var3}
What I must to do to set value of value1 to value4?
Let’s take this one line from your question:
As it stands, that will create a global variable (regardless of where the code is). Global variables are properties of the global object, which is
windowon browsers, so you can access that via bracketed notation with a string (e.g.,window["var1"]) as a couple of the answers here mention. But that’s only part of the story.If the code is at global scope, it’s fairly obvious you’re creating a global variable. If that line appears as-is in a function, it still creates a global variable — you’re falling prey to the Horror of Implicit Globals.
The moral of the story is: Use
varwhen creating variables:Now you’re explicitly creating a variable in the current scope — e.g., at global scope if that’s where the code is, or at function scope if that’s where the code is.
So global variables are properties of
window; how ’bout function variables, are they properties of an object? Yes, they are (it’s called the “variable object” in the spec, and it’s a very real thing, not a spec abstraction), but you have no means of accessing that object directly, there’s no symbol or name you can use to get at it. If you want to get a function’s variable using a string version of its name, your only option iseval, and don’t do that. Instead, refactor the code and make the thing you need to access the property of an object: