I’ve looked for solutions, but couldn’t find any that work.
I have a variable called onlyVideo.
"onlyVideo" the string gets passed into a function. I want to set the variable onlyVideo inside the function as something. How can I do that?
(There are a number of variables that could be called into the function, so I need it to work dynamically, not hard coded if statements.)
Edit: There’s probably a better way of doing what you’re attempting to do. I asked this early on in my JavaScript adventure. Check out how JavaScript objects work.
A simple intro:
// create JavaScript object
var obj = { "key1": 1 };
// assign - set "key2" to 2
obj.key2 = 2;
// read values
obj.key1 === 1;
obj.key2 === 2;
// read values with a string, same result as above
// but works with special characters and spaces
// and of course variables
obj["key1"] === 1;
obj["key2"] === 2;
// read with a variable
var key1Str = "key1";
obj[key1Str] === 1;
-
6What are you using this for? Are you absolutely sure you need to set it to a normal local variable, and an Object (Hash) won't work?Dogbert– Dogbert2011年04月10日 18:32:33 +00:00Commented Apr 10, 2011 at 18:32
-
mmm... I still don't quite grasp why you want to do this in a world with arrays. Anyway, some of your code and explanation would help a lot.Kevin Chavez– Kevin Chavez2011年04月10日 18:34:12 +00:00Commented Apr 10, 2011 at 18:34
-
i think we need more detail about what your ultimate goal ismcgrailm– mcgrailm2011年04月10日 18:35:32 +00:00Commented Apr 10, 2011 at 18:35
12 Answers 12
If it's a global variable then window[variableName]
or in your case window["onlyVideo"] should do the trick.
6 Comments
scope[property] or even this[property]this is context, what it points to depends on how the function is called. In JS, 50% of the time this is window unless you enable strict mode and this becomes undefined and will throw an error. Scope is something completely different and it's not an object (except global scope which is mirrored by the window object)WebWorkers (where self reffers to global scope, just as it does in browser, where it's equal to window) and Node.js, where global is the variable you want. And it newer works with local scopes, such as the function body.const using this method?Javascript has an eval() function for such occasions:
function (varString) {
var myVar = eval(varString);
// .....
}
Edit: Sorry, I think I skimmed the question too quickly. This will only get you the variable, to set it you need
function SetTo5(varString) {
var newValue = 5;
eval(varString + " = " + newValue);
}
or if using a string:
function SetToString(varString) {
var newValue = "string";
eval(varString + " = " + "'" + newValue + "'");
}
But I imagine there is a more appropriate way to accomplish what you're looking for? I don't think eval() is something you really want to use unless there's a great reason for it. eval()
7 Comments
window[varname] has the side-effect of introducing global variables, which might not be wanted. @Shaz I don't think you give modern JS interpreters enough credit. They are extremely fast, and parsing and executing a simple one line assignment operation is not going to spike anyone's CPU usage as long as it is not being done in a 1ms timer or tight loop.As far as eval vs. global variable solutions...
I think there are advantages to each but this is really a false dichotomy. If you are paranoid of the global namespace just create a temporary namespace & use the same technique.
var tempNamespace = {};
var myString = "myVarProperty";
tempNamespace[myString] = 5;
Pretty sure you could then access as tempNamespace.myVarProperty (now 5), avoiding using window for storage. (The string could also be put directly into the brackets)
3 Comments
var myString = "echoHello";
window[myString] = function() {
alert("Hello!");
}
echoHello();
Say no to the evil eval. Example here: https://jsfiddle.net/Shaz/WmA8t/
3 Comments
function aScope() { this[myString] = function() { alert("Hello!"); };};this is not refference to the local scope but to the object that the function is bound to during call.You can do like this
var name = "foo";
var value = "Hello foos";
eval("var "+name+" = '"+value+"';");
alert(foo);
Comments
You can access the window object as an associative array and set it that way
window["onlyVideo"] = "TEST";
document.write(onlyVideo);
Comments
The window['variableName'] method ONLY works if the variable is defined in the global scope. The correct answer is "Refactor". If you can provide an "Object" context then a possible general solution exists, but there are some variables which no global function could resolve based on the scope of the variable.
(function(){
var findMe = 'no way';
})();
Comments
If you're trying to access the property of an object, you have to start with the scope of window and go through each property of the object until you get to the one you want. Assuming that a.b.c has been defined somewhere else in the script, you can use the following:
var values = window;
var str = 'a.b.c'.values.split('.');
for(var i=0; i < str.length; i++)
values = values[str[i]];
This will work for getting the property of any object, no matter how deep it is.
4 Comments
name as the variable name, your example fails, but it works with other variable names. This may have to do with the Window object already having a name variable. Also, including the .value method caused failure. The ability to interpret deeply nested object variables is what I am looking for and your method indicates a good direction. Thanks.Uncaught TypeError: Cannot read property 'split' of undefinedIt can be done like this
(function(X, Y) {
// X is the local name of the 'class'
// Doo is default value if param X is empty
var X = (typeof X == 'string') ? X: 'Doo';
var Y = (typeof Y == 'string') ? Y: 'doo';
// this refers to the local X defined above
this[X] = function(doo) {
// object variable
this.doo = doo || 'doo it';
}
// prototypal inheritance for methods
// defined by another
this[X].prototype[Y] = function() {
return this.doo || 'doo';
};
// make X global
window[X] = this[X];
}('Dooa', 'dooa')); // give the names here
// test
doo = new Dooa('abc');
doo2 = new Dooa('def');
console.log(doo.dooa());
console.log(doo2.dooa());
Comments
The following code makes it easy to refer to each of your DIVs and other HTML elements in JavaScript. This code should be included just before the tag, so that all of the HTML elements have been seen. It should be followed by your JavaScript code.
// For each element with an id (example: 'MyDIV') in the body, create a variable
// for easy reference. An example is below.
var D=document;
var id={}; // All ID elements
var els=document.body.getElementsByTagName('*');
for (var i = 0; i < els.length; i++)
{
thisid = els[i].id;
if (!thisid)
continue;
val=D.getElementById(thisid);
id[thisid]=val;
}
// Usage:
id.MyDIV.innerHTML="hello";
Comments
Here, Short and Sweet If You Want to convert your answer into variable
const container = "foo"
// if you want foo as varible
eval(container)
according 2023 Javascript
3 Comments
eval for this.let me make it more clear
function changeStringToVariable(variable, value){
window[variable]=value
}
changeStringToVariable("name", "john doe");
console.log(name);
//this outputs: john doe
let file="newFile";
changeStringToVariable(file, "text file");
console.log(newFile);
//this outputs: text file