Is there a way to find JavaScript variable on the page (get it as an object) by its name? Variable name is available as a string constant.
标签:
javascript
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
If you are wanting a variable that is declared in the global context, it is attached to the window object. ex: window["variableName"]. All variables are a hash table value within their scope.
If you have to use dotted notation, then you will want to follow kennebec's suggestion, to navigate through the object hierarchy. eval() can work as well, but is a more expensive operation than is probably needed.
All JS objects (which variables are) are available within their scope as named properties of their parent object. Where no explicit parent exists, it is implicitly the
window
object.i.e.:
and for a complex object:
and this can be chained:
https://stackoverflow.com/a/17432007/1250044
You could use eval()
If your string references a 'deep' property of a global, like 'Yankee.console.format' you can step through the references:
If it's a global variable, you can look it up by name on the global object, since global variables are properties of the global object. On browsers, there's a global variable that refers to the global object called
window
, so:But global variables are a Bad Thing(tm).
To do this without globals, use your own object:
Both of the above work because in JavaScript, you can refer to an object property either with dot notation and a literal (
obj.foo
), or with bracketed notation and a string (obj["foo"]
), and in the latter case, the string can be the result of any expression, including a variable lookup.