简体   繁体   中英

javascript How do I “dereference” a variable's content for use as a variable name?

I want to reduce the I/O overhead of fetching information from the server using XMLHttpRequest() or ActiveXObject() , as appropriate, by making a general-purpose function for doing the fetch which then stores the fetched data using sessionStorage.<variable> . The trouble is, I don't know in advance what the variable names all are, and I intentionally don't want to know.

I was thinking that if there is some way to " dereference " a variable, like we can easily do in BASH , for example, this would be trivial. For example, if the fetched data was in newData, and the name of the file it was fetched from is in dataFile, and if the dereference syntax was, say $(<variableName>) , then one could write code like this to store and fetch the data:

//Store the data:
sessionStorage.$(dataFile) = newData;

//Fetch the data:

var storedData = sessionStorage.$(dataFile);

Get it? ... OK, now, how do I ACTUALLY do this?!

...The only other way around this I can see is VERY clumsy - make arrays, one with name, another with values - there MUST be an easier way! TIA.

As always, it is good to visit the docs first. There you can see, that sessionStorage (like localStorage or Map) has no properties at all (except a hidden property pointing to internal memory but thats another thing), but rather makes the data available through its get or set methods:

 sessionStorage.set("a name", "a value");

However the session/localStorage provides also global getters/setters, so in theory one can do:

  sessionStorage.name = "value";

If the keys name is dynamic one could use bracket notation:

   sessionStorage[aName] = aValue;

However, they havent it even mentioned in the docs, so this feature is neither widely supported nor a good coding style.

Try this. Not exactly sure I followed your question clearly but I would try this if you are having issues using the variable name as string within your other code.

var_param = GET_YOUR_VAR_SOMEHOW; // strip your params as needed
let f1 = { getVarName:var_param.toString()} // object = to f2
let f2 = 'getVarName'; // string = to f1 key

var storedData = sessionStorage.$(f1[f2]); // result of f1[f2] should be your incoming var string, de-referenced from any content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM