Use dynamic variable names in JavaScriptJavascript - set a variable using concatenation of stringsUsing string as variable name in JS?Create a new unique global variable each time a function is run in javascriptConcatenation in variable namesDynamic array names in jQueryHow to concatenate variable inside function name?How to put variable value inside another variable name in JavascriptCreate dynamic arrays using for loop with jquery/javascript can not access outside or cant access globalcreate variable name functionJavaScript have a variable in a variable nameHow do JavaScript closures work?How do I remove a property from a JavaScript object?Which equals operator (== vs ===) should be used in JavaScript comparisons?How do you check if a variable is an array in JavaScript?Set a default parameter value for a JavaScript functionHow do I include a JavaScript file in another JavaScript file?What does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?How to decide when to use Node.js?How do I remove a particular element from an array in JavaScript?
Remove color cast in darktable?
spatiotemporal regression
Why is it wrong to *implement* myself a known, published, widely believed to be secure crypto algorithm?
Why should password hash verification be time consistent?
date -d 'previous Monday" to display the preceding Monday
How is CoreiX like Corei5, i7 is related to Haswell, Ivy Bridge?
Can a surprised creature fall prone voluntarily on their turn?
Whats the purpose of lockedLoadData / uncached page build takes around a minute, spent in usleep
Electric kick drum pedal starts oscillating in such a way that it does not register hits
Translation of the latin word 'sit' in Thomas Aquinas' works
Best species to breed to intelligence
Has magnetic core memory been used beyond the Moon?
Why does increasing the sampling rate make implementing an anti-aliasing filter easier?
My perfect evil overlord plan... or is it?
What does formal training in a field mean?
Is there any evidence that democracy is linked causatively with improved outcomes?
Would encrypting a database protect against a compromised admin account?
When do you stop "pushing" a book?
Why did Captain America age?
What's the "magic similar to the Knock spell" referenced in the Dungeon of the Mad Mage adventure?
Is a vertical stabiliser needed for straight line flight in a glider?
A Cunning Riley Riddle
How did Arya survive this confrontation unscathed?
What is the name of meteoroids which hit Moon, Mars, or pretty much anything that isn’t the Earth?
Use dynamic variable names in JavaScript
Javascript - set a variable using concatenation of stringsUsing string as variable name in JS?Create a new unique global variable each time a function is run in javascriptConcatenation in variable namesDynamic array names in jQueryHow to concatenate variable inside function name?How to put variable value inside another variable name in JavascriptCreate dynamic arrays using for loop with jquery/javascript can not access outside or cant access globalcreate variable name functionJavaScript have a variable in a variable nameHow do JavaScript closures work?How do I remove a property from a JavaScript object?Which equals operator (== vs ===) should be used in JavaScript comparisons?How do you check if a variable is an array in JavaScript?Set a default parameter value for a JavaScript functionHow do I include a JavaScript file in another JavaScript file?What does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?How to decide when to use Node.js?How do I remove a particular element from an array in JavaScript?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
In PHP you can do amazing/horrendous things like this:
$a = 1;
$b = 2;
$c = 3;
$name = 'a';
echo $$name;
// prints 1
Is there any way of doing something like this with Javascript?
E.g. if I have a var name = 'the name of the variable'; can I get a reference to the variable with name name?
javascript dynamic-variables
add a comment |
In PHP you can do amazing/horrendous things like this:
$a = 1;
$b = 2;
$c = 3;
$name = 'a';
echo $$name;
// prints 1
Is there any way of doing something like this with Javascript?
E.g. if I have a var name = 'the name of the variable'; can I get a reference to the variable with name name?
javascript dynamic-variables
2
Possible dupe of stackoverflow.com/questions/724857/…, and stackoverflow.com/questions/1664282/…, but the accepted answer here better, IMO.
– goodeye
May 22 '13 at 22:41
add a comment |
In PHP you can do amazing/horrendous things like this:
$a = 1;
$b = 2;
$c = 3;
$name = 'a';
echo $$name;
// prints 1
Is there any way of doing something like this with Javascript?
E.g. if I have a var name = 'the name of the variable'; can I get a reference to the variable with name name?
javascript dynamic-variables
In PHP you can do amazing/horrendous things like this:
$a = 1;
$b = 2;
$c = 3;
$name = 'a';
echo $$name;
// prints 1
Is there any way of doing something like this with Javascript?
E.g. if I have a var name = 'the name of the variable'; can I get a reference to the variable with name name?
javascript dynamic-variables
javascript dynamic-variables
edited Aug 29 '14 at 5:38
user2864740
44.6k674151
44.6k674151
asked Feb 25 '11 at 12:19
FinbarrFinbarr
20k95484
20k95484
2
Possible dupe of stackoverflow.com/questions/724857/…, and stackoverflow.com/questions/1664282/…, but the accepted answer here better, IMO.
– goodeye
May 22 '13 at 22:41
add a comment |
2
Possible dupe of stackoverflow.com/questions/724857/…, and stackoverflow.com/questions/1664282/…, but the accepted answer here better, IMO.
– goodeye
May 22 '13 at 22:41
2
2
Possible dupe of stackoverflow.com/questions/724857/…, and stackoverflow.com/questions/1664282/…, but the accepted answer here better, IMO.
– goodeye
May 22 '13 at 22:41
Possible dupe of stackoverflow.com/questions/724857/…, and stackoverflow.com/questions/1664282/…, but the accepted answer here better, IMO.
– goodeye
May 22 '13 at 22:41
add a comment |
14 Answers
14
active
oldest
votes
Since ECMA-/Javascript is all about Objects and Contexts (which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object).
So if you create variables like this:
var a = 1,
b = 2,
c = 3;
In the Global scope (= NO function context), you implicitly write those variables into the Global object (= window in a browser).
Those can get accessed by using the "dot" or "bracket" notation:
var name = window.a;
or
var name = window['a'];
This only works for the global object in this particular instance, because the Variable Object of the Global Object is the window object itself. Within the Context of a function, you don't have direct access to the Activation Object. For instance:
function foobar()
this.a = 1;
this.b = 2;
var name = window['a']; // === undefined
alert(name);
name = this['a']; // === 1
alert(name);
new foobar();
new creates a new instance of a self-defined object (context). Without new the scope of the function would be also global (=window). This example would alert undefined and 1 respectively. If we would replace this.a = 1; this.b = 2 with:
var a = 1,
b = 2;
Both alert outputs would be undefined. In that scenario, the variables a and b would get stored in the Activation Object from foobar, which we cannot access (of course we could access those directly by calling a and b).
1
Another cool thing is that in this way you can add callback (start/end) for any global level function.
– antitoxic
Aug 7 '12 at 7:39
4
But what if my dynamic variable is local in a function? for example: function boink() var a = 1; // this will not work var dynamic = this['a']; // this also wont work var dynamic = ['a'];
– Kokodoko
Oct 28 '13 at 11:03
@Kokodoko—because this isn't "context" or a reference to a function's execution context (there is no way to reference an execution context, it's forbidden by the ECMA-262). this is set by how a function is called (or by bind), it's just an Object that has nothing to do with the execution context in which it's accessible.
– RobG
May 13 '15 at 2:55
If you need to access nested properties check out stackoverflow.com/questions/4244896/…
– Mr Br
Jun 22 '15 at 8:12
pointed me in the right direction with the bracket notation. Was stuck thinking dot notation only.
– Andrew
Mar 2 '17 at 20:29
|
show 1 more comment
eval is one option.
var a = 1;
var name = 'a';
document.write(eval(name)); // 1
10
No it shouldn't as eval is evil. Never use eval!
– EasyBB
Jan 18 '14 at 21:18
35
@EasyBB - if you're going to say never to use something, I't helpful to explain why. I have a situation in which I can't think of any other way to accomplish what I'm doing other than eval()
– Rampant Creative Group
Mar 25 '14 at 10:54
2
Eval poses a risk for attacks on end users and we'll it's not technically evil rather misunderstood and misused in a lost of cases. I've seen php responses which hold literal vars in it then use eval to run it. Though this shouldn't be used in this case as there are better methods. This question at hand eval should not be used at all as there are better methods overall and I'm sure a lot of us know this.
– EasyBB
Mar 25 '14 at 13:26
2
Via javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval --- "Let’s consider the arguments most frequently leveled against using eval: 1) It requires a compile and is therefore slow 2) What if a malicious script found its way into the eval argument? 3) It looks ugly 4) It inherits the execution context and this binding of the scope in which its invoked"
– mattLummus
May 13 '15 at 15:07
1
Here is how to create dynamic variables using eval: stackoverflow.com/a/13291766/5528600
– am2124429
Mar 21 '16 at 12:54
add a comment |
You can use the window object to get at it .
window['myVar']
window has a reference to all global variables and global functions you are using.
24
And needless to say, this one is safer than eval().
– Cray
Feb 25 '11 at 12:23
add a comment |
Just don't know what a bad answer gets so many votes. It's quite easy answer but you make it complex.
// If you want to get article_count
// var article_count = 1000;
var type = 'article';
this[type+'_count'] = 1000; // in a function we use "this";
alert(article_count);
9
"in a function we usethis" - If you want to access a global variable in this way, it is better to be explicit and use thewindowobject, notthis.thisis ambiguous.
– MrWhite
Aug 23 '15 at 23:25
add a comment |
a = 'varname';
str = a+' = '+'123';
eval(str)
alert(varname);
Try this...
add a comment |
This is an example :
for(var i=0; i<=3; i++)
window['p'+i] = "hello " + i;
alert(p0); // hello 0
alert(p1); // hello 1
alert(p2); // hello 2
alert(p3); // hello 3
Another example :
var myVariable = 'coco';
window[myVariable] = 'riko';
alert(coco); // display : riko
So, the value "coco" of myVariable becomes a variable coco.
Because all the variables in the global scope are properties of the Window object.
add a comment |
In Javascript you can use the fact that all properties are key value pairs. jAndy already mentioned this but I don't think his answer show how it can be exploited.
Usually you are not trying to create a variable to hold a variable name but are trying to generate variable names and then use them. PHP does it with $$var notation but Javascript doesn't need to because property keys are interchangeable with array keys.
var id = "abc";
var mine = ;
mine[id] = 123;
console.log(mine.abc);
gives 123. Usually you want to construct the variable which is why there is the indirection so you can also do it the other way around.
var mine = ;
mine.abc = 123;
console.log(mine["a"+"bc"]);
1
var someJsonObj = ; in a loop.... for(var i=0; i<=3; i++) someJsonObj[i] = []; , but i can be anything. so dynamically generated variables, all sit inside someJsonObj for easy reference.
– rajeev
Apr 7 '17 at 6:31
add a comment |
If you don't want to use a global object like window or global (node), you can try something like this:
var obj = ;
obj['whatever'] = 'There's no need to store even more stuff in a global object.';
console.log(obj['whatever']);
add a comment |
I needed to draw multiple FormData on the fly and object way worked well
var forms =
Then in my loops whereever i needed to create a form data i used
forms["formdata"+counter]=new FormData();
forms["formdata"+counter].append(var_name, var_value);
add a comment |
2019
TL;DR
evaloperator can run string expression in the context it called and return the value, also variables;literal objecttheoretically can do that[varName], but it blocked by definition.
So I come across this question and everyone here just play around without bringing a real solution. Thanks to @Axel Heider, who was approaching.
The right solution is eval
The almost most forgotten language operator. ( I think the most one is with )
so reserve word operator eval can dynamically run expression in the context it called. and return the result of that expression. we can use that to dynamicly return a value of a variable in a function context.
example:
function exmaple1()
var a = 1, b = 2, default = 3;
var name = 'a';
return eval(name)
example1() // return 1
function example2(option)
var a = 1, b = 2, defaultValue = 3;
switch(option)
case 'a': name = 'a'; break;
case 'b': name = 'b'; break;
default: name = 'defaultValue';
return eval (name);
example2('a') // return 1
example2('b') // return 2
example2() // return 3
Note that I always write explicitly the expression eval will run.
To avoid unnecessary surprises in the code. eval is very strong
But I'm sure you know that already
BTW, if it was legal we could use literal object to capture the variable name and value, but we can’t combine computed property names and property value shorthand, sadly, is invalid
functopn example( varName )
var var1 = 'foo', var2 ='bar'
var capture = [varName]
example('var1') //trow 'Uncaught SyntaxError: Unexpected token }`
add a comment |
what they mean is no, you can't.
there is no way to get it done.
so it was possible you could do something like this
function create(obj, const)
// where obj is an object and const is a variable name
function const ()
const.prototype.myProperty = property_value;
// .. more prototype
return new const();
having a create function just like the one implemented in ECMAScript 5.
4
Beware: const is a keyword in ES6
– Tejas Manohar
Nov 17 '15 at 9:00
4
...and prior to that was a future reserved word.
– T.J. Crowder
Dec 9 '15 at 16:23
there isevaloperator
– pery mimon
Jan 5 at 9:46
add a comment |
eval() did not work in my tests. But adding new JavaScript code to the DOM tree is possible. So here is a function that adds a new variable:
function createVariable(varName,varContent)
var scriptStr = "var "+varName+"= ""+varContent+"""
var node_scriptCode = document.createTextNode( scriptStr )
var node_script = document.createElement("script");
node_script.type = "text/javascript"
node_script.appendChild(node_scriptCode);
var node_head = document.getElementsByTagName("head")[0]
node_head.appendChild(node_script);
createVariable("dynamicVar", "some content")
console.log(dynamicVar)
2
small improvement, it is better to usevar node_head = document.getElementsByTagName("head")[0]instead of ID, as no one gives anid="head"to<head>:-)
– ddlab
Nov 9 '14 at 17:41
I do :) But thanks, now I can finally remove this `id="head" thing
– Axel Heider
May 4 '15 at 11:33
1
This just seems to be an overly complex way of creating a global variable?! (...and how does this answer the question?)
– MrWhite
Aug 23 '15 at 23:39
genius :) eval is the solution. Even if your code does not work
– pery mimon
Jan 4 at 18:27
add a comment |
use Object is great too.
var a=123
var b=234
var temp = "a":a,"b":b
console.log(temp["a"],temp["b"]);
add a comment |
Although this have an accepted answer I would like to add an observation:
In ES6 using let doesn't work:
/*this is NOT working*/
let t = "skyBlue",
m = "gold",
b = "tomato";
let color = window["b"];
console.log(color);However using var works
/*this IS working*/
var t = "skyBlue",
m = "gold",
b = "tomato";
let color = window["b"];
console.log(color);I hope this may be useful to some.
1
same applies toconst
– user4244405
Apr 19 at 8:26
add a comment |
protected by Community♦ Apr 11 '18 at 16:47
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
14 Answers
14
active
oldest
votes
14 Answers
14
active
oldest
votes
active
oldest
votes
active
oldest
votes
Since ECMA-/Javascript is all about Objects and Contexts (which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object).
So if you create variables like this:
var a = 1,
b = 2,
c = 3;
In the Global scope (= NO function context), you implicitly write those variables into the Global object (= window in a browser).
Those can get accessed by using the "dot" or "bracket" notation:
var name = window.a;
or
var name = window['a'];
This only works for the global object in this particular instance, because the Variable Object of the Global Object is the window object itself. Within the Context of a function, you don't have direct access to the Activation Object. For instance:
function foobar()
this.a = 1;
this.b = 2;
var name = window['a']; // === undefined
alert(name);
name = this['a']; // === 1
alert(name);
new foobar();
new creates a new instance of a self-defined object (context). Without new the scope of the function would be also global (=window). This example would alert undefined and 1 respectively. If we would replace this.a = 1; this.b = 2 with:
var a = 1,
b = 2;
Both alert outputs would be undefined. In that scenario, the variables a and b would get stored in the Activation Object from foobar, which we cannot access (of course we could access those directly by calling a and b).
1
Another cool thing is that in this way you can add callback (start/end) for any global level function.
– antitoxic
Aug 7 '12 at 7:39
4
But what if my dynamic variable is local in a function? for example: function boink() var a = 1; // this will not work var dynamic = this['a']; // this also wont work var dynamic = ['a'];
– Kokodoko
Oct 28 '13 at 11:03
@Kokodoko—because this isn't "context" or a reference to a function's execution context (there is no way to reference an execution context, it's forbidden by the ECMA-262). this is set by how a function is called (or by bind), it's just an Object that has nothing to do with the execution context in which it's accessible.
– RobG
May 13 '15 at 2:55
If you need to access nested properties check out stackoverflow.com/questions/4244896/…
– Mr Br
Jun 22 '15 at 8:12
pointed me in the right direction with the bracket notation. Was stuck thinking dot notation only.
– Andrew
Mar 2 '17 at 20:29
|
show 1 more comment
Since ECMA-/Javascript is all about Objects and Contexts (which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object).
So if you create variables like this:
var a = 1,
b = 2,
c = 3;
In the Global scope (= NO function context), you implicitly write those variables into the Global object (= window in a browser).
Those can get accessed by using the "dot" or "bracket" notation:
var name = window.a;
or
var name = window['a'];
This only works for the global object in this particular instance, because the Variable Object of the Global Object is the window object itself. Within the Context of a function, you don't have direct access to the Activation Object. For instance:
function foobar()
this.a = 1;
this.b = 2;
var name = window['a']; // === undefined
alert(name);
name = this['a']; // === 1
alert(name);
new foobar();
new creates a new instance of a self-defined object (context). Without new the scope of the function would be also global (=window). This example would alert undefined and 1 respectively. If we would replace this.a = 1; this.b = 2 with:
var a = 1,
b = 2;
Both alert outputs would be undefined. In that scenario, the variables a and b would get stored in the Activation Object from foobar, which we cannot access (of course we could access those directly by calling a and b).
1
Another cool thing is that in this way you can add callback (start/end) for any global level function.
– antitoxic
Aug 7 '12 at 7:39
4
But what if my dynamic variable is local in a function? for example: function boink() var a = 1; // this will not work var dynamic = this['a']; // this also wont work var dynamic = ['a'];
– Kokodoko
Oct 28 '13 at 11:03
@Kokodoko—because this isn't "context" or a reference to a function's execution context (there is no way to reference an execution context, it's forbidden by the ECMA-262). this is set by how a function is called (or by bind), it's just an Object that has nothing to do with the execution context in which it's accessible.
– RobG
May 13 '15 at 2:55
If you need to access nested properties check out stackoverflow.com/questions/4244896/…
– Mr Br
Jun 22 '15 at 8:12
pointed me in the right direction with the bracket notation. Was stuck thinking dot notation only.
– Andrew
Mar 2 '17 at 20:29
|
show 1 more comment
Since ECMA-/Javascript is all about Objects and Contexts (which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object).
So if you create variables like this:
var a = 1,
b = 2,
c = 3;
In the Global scope (= NO function context), you implicitly write those variables into the Global object (= window in a browser).
Those can get accessed by using the "dot" or "bracket" notation:
var name = window.a;
or
var name = window['a'];
This only works for the global object in this particular instance, because the Variable Object of the Global Object is the window object itself. Within the Context of a function, you don't have direct access to the Activation Object. For instance:
function foobar()
this.a = 1;
this.b = 2;
var name = window['a']; // === undefined
alert(name);
name = this['a']; // === 1
alert(name);
new foobar();
new creates a new instance of a self-defined object (context). Without new the scope of the function would be also global (=window). This example would alert undefined and 1 respectively. If we would replace this.a = 1; this.b = 2 with:
var a = 1,
b = 2;
Both alert outputs would be undefined. In that scenario, the variables a and b would get stored in the Activation Object from foobar, which we cannot access (of course we could access those directly by calling a and b).
Since ECMA-/Javascript is all about Objects and Contexts (which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object).
So if you create variables like this:
var a = 1,
b = 2,
c = 3;
In the Global scope (= NO function context), you implicitly write those variables into the Global object (= window in a browser).
Those can get accessed by using the "dot" or "bracket" notation:
var name = window.a;
or
var name = window['a'];
This only works for the global object in this particular instance, because the Variable Object of the Global Object is the window object itself. Within the Context of a function, you don't have direct access to the Activation Object. For instance:
function foobar()
this.a = 1;
this.b = 2;
var name = window['a']; // === undefined
alert(name);
name = this['a']; // === 1
alert(name);
new foobar();
new creates a new instance of a self-defined object (context). Without new the scope of the function would be also global (=window). This example would alert undefined and 1 respectively. If we would replace this.a = 1; this.b = 2 with:
var a = 1,
b = 2;
Both alert outputs would be undefined. In that scenario, the variables a and b would get stored in the Activation Object from foobar, which we cannot access (of course we could access those directly by calling a and b).
edited Dec 2 '12 at 23:54
McGarnagle
87.3k24190233
87.3k24190233
answered Feb 25 '11 at 12:23
jAndyjAndy
179k43268330
179k43268330
1
Another cool thing is that in this way you can add callback (start/end) for any global level function.
– antitoxic
Aug 7 '12 at 7:39
4
But what if my dynamic variable is local in a function? for example: function boink() var a = 1; // this will not work var dynamic = this['a']; // this also wont work var dynamic = ['a'];
– Kokodoko
Oct 28 '13 at 11:03
@Kokodoko—because this isn't "context" or a reference to a function's execution context (there is no way to reference an execution context, it's forbidden by the ECMA-262). this is set by how a function is called (or by bind), it's just an Object that has nothing to do with the execution context in which it's accessible.
– RobG
May 13 '15 at 2:55
If you need to access nested properties check out stackoverflow.com/questions/4244896/…
– Mr Br
Jun 22 '15 at 8:12
pointed me in the right direction with the bracket notation. Was stuck thinking dot notation only.
– Andrew
Mar 2 '17 at 20:29
|
show 1 more comment
1
Another cool thing is that in this way you can add callback (start/end) for any global level function.
– antitoxic
Aug 7 '12 at 7:39
4
But what if my dynamic variable is local in a function? for example: function boink() var a = 1; // this will not work var dynamic = this['a']; // this also wont work var dynamic = ['a'];
– Kokodoko
Oct 28 '13 at 11:03
@Kokodoko—because this isn't "context" or a reference to a function's execution context (there is no way to reference an execution context, it's forbidden by the ECMA-262). this is set by how a function is called (or by bind), it's just an Object that has nothing to do with the execution context in which it's accessible.
– RobG
May 13 '15 at 2:55
If you need to access nested properties check out stackoverflow.com/questions/4244896/…
– Mr Br
Jun 22 '15 at 8:12
pointed me in the right direction with the bracket notation. Was stuck thinking dot notation only.
– Andrew
Mar 2 '17 at 20:29
1
1
Another cool thing is that in this way you can add callback (start/end) for any global level function.
– antitoxic
Aug 7 '12 at 7:39
Another cool thing is that in this way you can add callback (start/end) for any global level function.
– antitoxic
Aug 7 '12 at 7:39
4
4
But what if my dynamic variable is local in a function? for example: function boink() var a = 1; // this will not work var dynamic = this['a']; // this also wont work var dynamic = ['a'];
– Kokodoko
Oct 28 '13 at 11:03
But what if my dynamic variable is local in a function? for example: function boink() var a = 1; // this will not work var dynamic = this['a']; // this also wont work var dynamic = ['a'];
– Kokodoko
Oct 28 '13 at 11:03
@Kokodoko—because this isn't "context" or a reference to a function's execution context (there is no way to reference an execution context, it's forbidden by the ECMA-262). this is set by how a function is called (or by bind), it's just an Object that has nothing to do with the execution context in which it's accessible.
– RobG
May 13 '15 at 2:55
@Kokodoko—because this isn't "context" or a reference to a function's execution context (there is no way to reference an execution context, it's forbidden by the ECMA-262). this is set by how a function is called (or by bind), it's just an Object that has nothing to do with the execution context in which it's accessible.
– RobG
May 13 '15 at 2:55
If you need to access nested properties check out stackoverflow.com/questions/4244896/…
– Mr Br
Jun 22 '15 at 8:12
If you need to access nested properties check out stackoverflow.com/questions/4244896/…
– Mr Br
Jun 22 '15 at 8:12
pointed me in the right direction with the bracket notation. Was stuck thinking dot notation only.
– Andrew
Mar 2 '17 at 20:29
pointed me in the right direction with the bracket notation. Was stuck thinking dot notation only.
– Andrew
Mar 2 '17 at 20:29
|
show 1 more comment
eval is one option.
var a = 1;
var name = 'a';
document.write(eval(name)); // 1
10
No it shouldn't as eval is evil. Never use eval!
– EasyBB
Jan 18 '14 at 21:18
35
@EasyBB - if you're going to say never to use something, I't helpful to explain why. I have a situation in which I can't think of any other way to accomplish what I'm doing other than eval()
– Rampant Creative Group
Mar 25 '14 at 10:54
2
Eval poses a risk for attacks on end users and we'll it's not technically evil rather misunderstood and misused in a lost of cases. I've seen php responses which hold literal vars in it then use eval to run it. Though this shouldn't be used in this case as there are better methods. This question at hand eval should not be used at all as there are better methods overall and I'm sure a lot of us know this.
– EasyBB
Mar 25 '14 at 13:26
2
Via javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval --- "Let’s consider the arguments most frequently leveled against using eval: 1) It requires a compile and is therefore slow 2) What if a malicious script found its way into the eval argument? 3) It looks ugly 4) It inherits the execution context and this binding of the scope in which its invoked"
– mattLummus
May 13 '15 at 15:07
1
Here is how to create dynamic variables using eval: stackoverflow.com/a/13291766/5528600
– am2124429
Mar 21 '16 at 12:54
add a comment |
eval is one option.
var a = 1;
var name = 'a';
document.write(eval(name)); // 1
10
No it shouldn't as eval is evil. Never use eval!
– EasyBB
Jan 18 '14 at 21:18
35
@EasyBB - if you're going to say never to use something, I't helpful to explain why. I have a situation in which I can't think of any other way to accomplish what I'm doing other than eval()
– Rampant Creative Group
Mar 25 '14 at 10:54
2
Eval poses a risk for attacks on end users and we'll it's not technically evil rather misunderstood and misused in a lost of cases. I've seen php responses which hold literal vars in it then use eval to run it. Though this shouldn't be used in this case as there are better methods. This question at hand eval should not be used at all as there are better methods overall and I'm sure a lot of us know this.
– EasyBB
Mar 25 '14 at 13:26
2
Via javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval --- "Let’s consider the arguments most frequently leveled against using eval: 1) It requires a compile and is therefore slow 2) What if a malicious script found its way into the eval argument? 3) It looks ugly 4) It inherits the execution context and this binding of the scope in which its invoked"
– mattLummus
May 13 '15 at 15:07
1
Here is how to create dynamic variables using eval: stackoverflow.com/a/13291766/5528600
– am2124429
Mar 21 '16 at 12:54
add a comment |
eval is one option.
var a = 1;
var name = 'a';
document.write(eval(name)); // 1
eval is one option.
var a = 1;
var name = 'a';
document.write(eval(name)); // 1
answered Feb 25 '11 at 12:22
erickberickb
4,82621919
4,82621919
10
No it shouldn't as eval is evil. Never use eval!
– EasyBB
Jan 18 '14 at 21:18
35
@EasyBB - if you're going to say never to use something, I't helpful to explain why. I have a situation in which I can't think of any other way to accomplish what I'm doing other than eval()
– Rampant Creative Group
Mar 25 '14 at 10:54
2
Eval poses a risk for attacks on end users and we'll it's not technically evil rather misunderstood and misused in a lost of cases. I've seen php responses which hold literal vars in it then use eval to run it. Though this shouldn't be used in this case as there are better methods. This question at hand eval should not be used at all as there are better methods overall and I'm sure a lot of us know this.
– EasyBB
Mar 25 '14 at 13:26
2
Via javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval --- "Let’s consider the arguments most frequently leveled against using eval: 1) It requires a compile and is therefore slow 2) What if a malicious script found its way into the eval argument? 3) It looks ugly 4) It inherits the execution context and this binding of the scope in which its invoked"
– mattLummus
May 13 '15 at 15:07
1
Here is how to create dynamic variables using eval: stackoverflow.com/a/13291766/5528600
– am2124429
Mar 21 '16 at 12:54
add a comment |
10
No it shouldn't as eval is evil. Never use eval!
– EasyBB
Jan 18 '14 at 21:18
35
@EasyBB - if you're going to say never to use something, I't helpful to explain why. I have a situation in which I can't think of any other way to accomplish what I'm doing other than eval()
– Rampant Creative Group
Mar 25 '14 at 10:54
2
Eval poses a risk for attacks on end users and we'll it's not technically evil rather misunderstood and misused in a lost of cases. I've seen php responses which hold literal vars in it then use eval to run it. Though this shouldn't be used in this case as there are better methods. This question at hand eval should not be used at all as there are better methods overall and I'm sure a lot of us know this.
– EasyBB
Mar 25 '14 at 13:26
2
Via javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval --- "Let’s consider the arguments most frequently leveled against using eval: 1) It requires a compile and is therefore slow 2) What if a malicious script found its way into the eval argument? 3) It looks ugly 4) It inherits the execution context and this binding of the scope in which its invoked"
– mattLummus
May 13 '15 at 15:07
1
Here is how to create dynamic variables using eval: stackoverflow.com/a/13291766/5528600
– am2124429
Mar 21 '16 at 12:54
10
10
No it shouldn't as eval is evil. Never use eval!
– EasyBB
Jan 18 '14 at 21:18
No it shouldn't as eval is evil. Never use eval!
– EasyBB
Jan 18 '14 at 21:18
35
35
@EasyBB - if you're going to say never to use something, I't helpful to explain why. I have a situation in which I can't think of any other way to accomplish what I'm doing other than eval()
– Rampant Creative Group
Mar 25 '14 at 10:54
@EasyBB - if you're going to say never to use something, I't helpful to explain why. I have a situation in which I can't think of any other way to accomplish what I'm doing other than eval()
– Rampant Creative Group
Mar 25 '14 at 10:54
2
2
Eval poses a risk for attacks on end users and we'll it's not technically evil rather misunderstood and misused in a lost of cases. I've seen php responses which hold literal vars in it then use eval to run it. Though this shouldn't be used in this case as there are better methods. This question at hand eval should not be used at all as there are better methods overall and I'm sure a lot of us know this.
– EasyBB
Mar 25 '14 at 13:26
Eval poses a risk for attacks on end users and we'll it's not technically evil rather misunderstood and misused in a lost of cases. I've seen php responses which hold literal vars in it then use eval to run it. Though this shouldn't be used in this case as there are better methods. This question at hand eval should not be used at all as there are better methods overall and I'm sure a lot of us know this.
– EasyBB
Mar 25 '14 at 13:26
2
2
Via javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval --- "Let’s consider the arguments most frequently leveled against using eval: 1) It requires a compile and is therefore slow 2) What if a malicious script found its way into the eval argument? 3) It looks ugly 4) It inherits the execution context and this binding of the scope in which its invoked"
– mattLummus
May 13 '15 at 15:07
Via javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval --- "Let’s consider the arguments most frequently leveled against using eval: 1) It requires a compile and is therefore slow 2) What if a malicious script found its way into the eval argument? 3) It looks ugly 4) It inherits the execution context and this binding of the scope in which its invoked"
– mattLummus
May 13 '15 at 15:07
1
1
Here is how to create dynamic variables using eval: stackoverflow.com/a/13291766/5528600
– am2124429
Mar 21 '16 at 12:54
Here is how to create dynamic variables using eval: stackoverflow.com/a/13291766/5528600
– am2124429
Mar 21 '16 at 12:54
add a comment |
You can use the window object to get at it .
window['myVar']
window has a reference to all global variables and global functions you are using.
24
And needless to say, this one is safer than eval().
– Cray
Feb 25 '11 at 12:23
add a comment |
You can use the window object to get at it .
window['myVar']
window has a reference to all global variables and global functions you are using.
24
And needless to say, this one is safer than eval().
– Cray
Feb 25 '11 at 12:23
add a comment |
You can use the window object to get at it .
window['myVar']
window has a reference to all global variables and global functions you are using.
You can use the window object to get at it .
window['myVar']
window has a reference to all global variables and global functions you are using.
edited Mar 30 '18 at 12:04
Sebastian Palma
16.5k42236
16.5k42236
answered Feb 25 '11 at 12:21
JohnPJohnP
42.8k891129
42.8k891129
24
And needless to say, this one is safer than eval().
– Cray
Feb 25 '11 at 12:23
add a comment |
24
And needless to say, this one is safer than eval().
– Cray
Feb 25 '11 at 12:23
24
24
And needless to say, this one is safer than eval().
– Cray
Feb 25 '11 at 12:23
And needless to say, this one is safer than eval().
– Cray
Feb 25 '11 at 12:23
add a comment |
Just don't know what a bad answer gets so many votes. It's quite easy answer but you make it complex.
// If you want to get article_count
// var article_count = 1000;
var type = 'article';
this[type+'_count'] = 1000; // in a function we use "this";
alert(article_count);
9
"in a function we usethis" - If you want to access a global variable in this way, it is better to be explicit and use thewindowobject, notthis.thisis ambiguous.
– MrWhite
Aug 23 '15 at 23:25
add a comment |
Just don't know what a bad answer gets so many votes. It's quite easy answer but you make it complex.
// If you want to get article_count
// var article_count = 1000;
var type = 'article';
this[type+'_count'] = 1000; // in a function we use "this";
alert(article_count);
9
"in a function we usethis" - If you want to access a global variable in this way, it is better to be explicit and use thewindowobject, notthis.thisis ambiguous.
– MrWhite
Aug 23 '15 at 23:25
add a comment |
Just don't know what a bad answer gets so many votes. It's quite easy answer but you make it complex.
// If you want to get article_count
// var article_count = 1000;
var type = 'article';
this[type+'_count'] = 1000; // in a function we use "this";
alert(article_count);
Just don't know what a bad answer gets so many votes. It's quite easy answer but you make it complex.
// If you want to get article_count
// var article_count = 1000;
var type = 'article';
this[type+'_count'] = 1000; // in a function we use "this";
alert(article_count);
edited Jan 21 '15 at 9:39
shkschneider
11.3k114596
11.3k114596
answered Jan 21 '15 at 9:11
Terry LinTerry Lin
1,5741319
1,5741319
9
"in a function we usethis" - If you want to access a global variable in this way, it is better to be explicit and use thewindowobject, notthis.thisis ambiguous.
– MrWhite
Aug 23 '15 at 23:25
add a comment |
9
"in a function we usethis" - If you want to access a global variable in this way, it is better to be explicit and use thewindowobject, notthis.thisis ambiguous.
– MrWhite
Aug 23 '15 at 23:25
9
9
"in a function we use
this" - If you want to access a global variable in this way, it is better to be explicit and use the window object, not this. this is ambiguous.– MrWhite
Aug 23 '15 at 23:25
"in a function we use
this" - If you want to access a global variable in this way, it is better to be explicit and use the window object, not this. this is ambiguous.– MrWhite
Aug 23 '15 at 23:25
add a comment |
a = 'varname';
str = a+' = '+'123';
eval(str)
alert(varname);
Try this...
add a comment |
a = 'varname';
str = a+' = '+'123';
eval(str)
alert(varname);
Try this...
add a comment |
a = 'varname';
str = a+' = '+'123';
eval(str)
alert(varname);
Try this...
a = 'varname';
str = a+' = '+'123';
eval(str)
alert(varname);
Try this...
answered Feb 25 '11 at 12:23
amitchdamitchd
91958
91958
add a comment |
add a comment |
This is an example :
for(var i=0; i<=3; i++)
window['p'+i] = "hello " + i;
alert(p0); // hello 0
alert(p1); // hello 1
alert(p2); // hello 2
alert(p3); // hello 3
Another example :
var myVariable = 'coco';
window[myVariable] = 'riko';
alert(coco); // display : riko
So, the value "coco" of myVariable becomes a variable coco.
Because all the variables in the global scope are properties of the Window object.
add a comment |
This is an example :
for(var i=0; i<=3; i++)
window['p'+i] = "hello " + i;
alert(p0); // hello 0
alert(p1); // hello 1
alert(p2); // hello 2
alert(p3); // hello 3
Another example :
var myVariable = 'coco';
window[myVariable] = 'riko';
alert(coco); // display : riko
So, the value "coco" of myVariable becomes a variable coco.
Because all the variables in the global scope are properties of the Window object.
add a comment |
This is an example :
for(var i=0; i<=3; i++)
window['p'+i] = "hello " + i;
alert(p0); // hello 0
alert(p1); // hello 1
alert(p2); // hello 2
alert(p3); // hello 3
Another example :
var myVariable = 'coco';
window[myVariable] = 'riko';
alert(coco); // display : riko
So, the value "coco" of myVariable becomes a variable coco.
Because all the variables in the global scope are properties of the Window object.
This is an example :
for(var i=0; i<=3; i++)
window['p'+i] = "hello " + i;
alert(p0); // hello 0
alert(p1); // hello 1
alert(p2); // hello 2
alert(p3); // hello 3
Another example :
var myVariable = 'coco';
window[myVariable] = 'riko';
alert(coco); // display : riko
So, the value "coco" of myVariable becomes a variable coco.
Because all the variables in the global scope are properties of the Window object.
edited Nov 18 '16 at 12:05
answered Jan 24 '15 at 20:55
AzodiumAzodium
1,07988
1,07988
add a comment |
add a comment |
In Javascript you can use the fact that all properties are key value pairs. jAndy already mentioned this but I don't think his answer show how it can be exploited.
Usually you are not trying to create a variable to hold a variable name but are trying to generate variable names and then use them. PHP does it with $$var notation but Javascript doesn't need to because property keys are interchangeable with array keys.
var id = "abc";
var mine = ;
mine[id] = 123;
console.log(mine.abc);
gives 123. Usually you want to construct the variable which is why there is the indirection so you can also do it the other way around.
var mine = ;
mine.abc = 123;
console.log(mine["a"+"bc"]);
1
var someJsonObj = ; in a loop.... for(var i=0; i<=3; i++) someJsonObj[i] = []; , but i can be anything. so dynamically generated variables, all sit inside someJsonObj for easy reference.
– rajeev
Apr 7 '17 at 6:31
add a comment |
In Javascript you can use the fact that all properties are key value pairs. jAndy already mentioned this but I don't think his answer show how it can be exploited.
Usually you are not trying to create a variable to hold a variable name but are trying to generate variable names and then use them. PHP does it with $$var notation but Javascript doesn't need to because property keys are interchangeable with array keys.
var id = "abc";
var mine = ;
mine[id] = 123;
console.log(mine.abc);
gives 123. Usually you want to construct the variable which is why there is the indirection so you can also do it the other way around.
var mine = ;
mine.abc = 123;
console.log(mine["a"+"bc"]);
1
var someJsonObj = ; in a loop.... for(var i=0; i<=3; i++) someJsonObj[i] = []; , but i can be anything. so dynamically generated variables, all sit inside someJsonObj for easy reference.
– rajeev
Apr 7 '17 at 6:31
add a comment |
In Javascript you can use the fact that all properties are key value pairs. jAndy already mentioned this but I don't think his answer show how it can be exploited.
Usually you are not trying to create a variable to hold a variable name but are trying to generate variable names and then use them. PHP does it with $$var notation but Javascript doesn't need to because property keys are interchangeable with array keys.
var id = "abc";
var mine = ;
mine[id] = 123;
console.log(mine.abc);
gives 123. Usually you want to construct the variable which is why there is the indirection so you can also do it the other way around.
var mine = ;
mine.abc = 123;
console.log(mine["a"+"bc"]);
In Javascript you can use the fact that all properties are key value pairs. jAndy already mentioned this but I don't think his answer show how it can be exploited.
Usually you are not trying to create a variable to hold a variable name but are trying to generate variable names and then use them. PHP does it with $$var notation but Javascript doesn't need to because property keys are interchangeable with array keys.
var id = "abc";
var mine = ;
mine[id] = 123;
console.log(mine.abc);
gives 123. Usually you want to construct the variable which is why there is the indirection so you can also do it the other way around.
var mine = ;
mine.abc = 123;
console.log(mine["a"+"bc"]);
answered Nov 27 '14 at 2:42
David NewcombDavid Newcomb
9,04233449
9,04233449
1
var someJsonObj = ; in a loop.... for(var i=0; i<=3; i++) someJsonObj[i] = []; , but i can be anything. so dynamically generated variables, all sit inside someJsonObj for easy reference.
– rajeev
Apr 7 '17 at 6:31
add a comment |
1
var someJsonObj = ; in a loop.... for(var i=0; i<=3; i++) someJsonObj[i] = []; , but i can be anything. so dynamically generated variables, all sit inside someJsonObj for easy reference.
– rajeev
Apr 7 '17 at 6:31
1
1
var someJsonObj = ; in a loop.... for(var i=0; i<=3; i++) someJsonObj[i] = []; , but i can be anything. so dynamically generated variables, all sit inside someJsonObj for easy reference.
– rajeev
Apr 7 '17 at 6:31
var someJsonObj = ; in a loop.... for(var i=0; i<=3; i++) someJsonObj[i] = []; , but i can be anything. so dynamically generated variables, all sit inside someJsonObj for easy reference.
– rajeev
Apr 7 '17 at 6:31
add a comment |
If you don't want to use a global object like window or global (node), you can try something like this:
var obj = ;
obj['whatever'] = 'There's no need to store even more stuff in a global object.';
console.log(obj['whatever']);
add a comment |
If you don't want to use a global object like window or global (node), you can try something like this:
var obj = ;
obj['whatever'] = 'There's no need to store even more stuff in a global object.';
console.log(obj['whatever']);
add a comment |
If you don't want to use a global object like window or global (node), you can try something like this:
var obj = ;
obj['whatever'] = 'There's no need to store even more stuff in a global object.';
console.log(obj['whatever']);
If you don't want to use a global object like window or global (node), you can try something like this:
var obj = ;
obj['whatever'] = 'There's no need to store even more stuff in a global object.';
console.log(obj['whatever']);
answered Jan 30 '15 at 0:06
Brent BarbataBrent Barbata
2,63811920
2,63811920
add a comment |
add a comment |
I needed to draw multiple FormData on the fly and object way worked well
var forms =
Then in my loops whereever i needed to create a form data i used
forms["formdata"+counter]=new FormData();
forms["formdata"+counter].append(var_name, var_value);
add a comment |
I needed to draw multiple FormData on the fly and object way worked well
var forms =
Then in my loops whereever i needed to create a form data i used
forms["formdata"+counter]=new FormData();
forms["formdata"+counter].append(var_name, var_value);
add a comment |
I needed to draw multiple FormData on the fly and object way worked well
var forms =
Then in my loops whereever i needed to create a form data i used
forms["formdata"+counter]=new FormData();
forms["formdata"+counter].append(var_name, var_value);
I needed to draw multiple FormData on the fly and object way worked well
var forms =
Then in my loops whereever i needed to create a form data i used
forms["formdata"+counter]=new FormData();
forms["formdata"+counter].append(var_name, var_value);
answered Sep 17 '17 at 23:21
TalhaTalha
797812
797812
add a comment |
add a comment |
2019
TL;DR
evaloperator can run string expression in the context it called and return the value, also variables;literal objecttheoretically can do that[varName], but it blocked by definition.
So I come across this question and everyone here just play around without bringing a real solution. Thanks to @Axel Heider, who was approaching.
The right solution is eval
The almost most forgotten language operator. ( I think the most one is with )
so reserve word operator eval can dynamically run expression in the context it called. and return the result of that expression. we can use that to dynamicly return a value of a variable in a function context.
example:
function exmaple1()
var a = 1, b = 2, default = 3;
var name = 'a';
return eval(name)
example1() // return 1
function example2(option)
var a = 1, b = 2, defaultValue = 3;
switch(option)
case 'a': name = 'a'; break;
case 'b': name = 'b'; break;
default: name = 'defaultValue';
return eval (name);
example2('a') // return 1
example2('b') // return 2
example2() // return 3
Note that I always write explicitly the expression eval will run.
To avoid unnecessary surprises in the code. eval is very strong
But I'm sure you know that already
BTW, if it was legal we could use literal object to capture the variable name and value, but we can’t combine computed property names and property value shorthand, sadly, is invalid
functopn example( varName )
var var1 = 'foo', var2 ='bar'
var capture = [varName]
example('var1') //trow 'Uncaught SyntaxError: Unexpected token }`
add a comment |
2019
TL;DR
evaloperator can run string expression in the context it called and return the value, also variables;literal objecttheoretically can do that[varName], but it blocked by definition.
So I come across this question and everyone here just play around without bringing a real solution. Thanks to @Axel Heider, who was approaching.
The right solution is eval
The almost most forgotten language operator. ( I think the most one is with )
so reserve word operator eval can dynamically run expression in the context it called. and return the result of that expression. we can use that to dynamicly return a value of a variable in a function context.
example:
function exmaple1()
var a = 1, b = 2, default = 3;
var name = 'a';
return eval(name)
example1() // return 1
function example2(option)
var a = 1, b = 2, defaultValue = 3;
switch(option)
case 'a': name = 'a'; break;
case 'b': name = 'b'; break;
default: name = 'defaultValue';
return eval (name);
example2('a') // return 1
example2('b') // return 2
example2() // return 3
Note that I always write explicitly the expression eval will run.
To avoid unnecessary surprises in the code. eval is very strong
But I'm sure you know that already
BTW, if it was legal we could use literal object to capture the variable name and value, but we can’t combine computed property names and property value shorthand, sadly, is invalid
functopn example( varName )
var var1 = 'foo', var2 ='bar'
var capture = [varName]
example('var1') //trow 'Uncaught SyntaxError: Unexpected token }`
add a comment |
2019
TL;DR
evaloperator can run string expression in the context it called and return the value, also variables;literal objecttheoretically can do that[varName], but it blocked by definition.
So I come across this question and everyone here just play around without bringing a real solution. Thanks to @Axel Heider, who was approaching.
The right solution is eval
The almost most forgotten language operator. ( I think the most one is with )
so reserve word operator eval can dynamically run expression in the context it called. and return the result of that expression. we can use that to dynamicly return a value of a variable in a function context.
example:
function exmaple1()
var a = 1, b = 2, default = 3;
var name = 'a';
return eval(name)
example1() // return 1
function example2(option)
var a = 1, b = 2, defaultValue = 3;
switch(option)
case 'a': name = 'a'; break;
case 'b': name = 'b'; break;
default: name = 'defaultValue';
return eval (name);
example2('a') // return 1
example2('b') // return 2
example2() // return 3
Note that I always write explicitly the expression eval will run.
To avoid unnecessary surprises in the code. eval is very strong
But I'm sure you know that already
BTW, if it was legal we could use literal object to capture the variable name and value, but we can’t combine computed property names and property value shorthand, sadly, is invalid
functopn example( varName )
var var1 = 'foo', var2 ='bar'
var capture = [varName]
example('var1') //trow 'Uncaught SyntaxError: Unexpected token }`
2019
TL;DR
evaloperator can run string expression in the context it called and return the value, also variables;literal objecttheoretically can do that[varName], but it blocked by definition.
So I come across this question and everyone here just play around without bringing a real solution. Thanks to @Axel Heider, who was approaching.
The right solution is eval
The almost most forgotten language operator. ( I think the most one is with )
so reserve word operator eval can dynamically run expression in the context it called. and return the result of that expression. we can use that to dynamicly return a value of a variable in a function context.
example:
function exmaple1()
var a = 1, b = 2, default = 3;
var name = 'a';
return eval(name)
example1() // return 1
function example2(option)
var a = 1, b = 2, defaultValue = 3;
switch(option)
case 'a': name = 'a'; break;
case 'b': name = 'b'; break;
default: name = 'defaultValue';
return eval (name);
example2('a') // return 1
example2('b') // return 2
example2() // return 3
Note that I always write explicitly the expression eval will run.
To avoid unnecessary surprises in the code. eval is very strong
But I'm sure you know that already
BTW, if it was legal we could use literal object to capture the variable name and value, but we can’t combine computed property names and property value shorthand, sadly, is invalid
functopn example( varName )
var var1 = 'foo', var2 ='bar'
var capture = [varName]
example('var1') //trow 'Uncaught SyntaxError: Unexpected token }`
edited Jan 31 at 10:06
answered Jan 4 at 19:08
pery mimonpery mimon
2,52522231
2,52522231
add a comment |
add a comment |
what they mean is no, you can't.
there is no way to get it done.
so it was possible you could do something like this
function create(obj, const)
// where obj is an object and const is a variable name
function const ()
const.prototype.myProperty = property_value;
// .. more prototype
return new const();
having a create function just like the one implemented in ECMAScript 5.
4
Beware: const is a keyword in ES6
– Tejas Manohar
Nov 17 '15 at 9:00
4
...and prior to that was a future reserved word.
– T.J. Crowder
Dec 9 '15 at 16:23
there isevaloperator
– pery mimon
Jan 5 at 9:46
add a comment |
what they mean is no, you can't.
there is no way to get it done.
so it was possible you could do something like this
function create(obj, const)
// where obj is an object and const is a variable name
function const ()
const.prototype.myProperty = property_value;
// .. more prototype
return new const();
having a create function just like the one implemented in ECMAScript 5.
4
Beware: const is a keyword in ES6
– Tejas Manohar
Nov 17 '15 at 9:00
4
...and prior to that was a future reserved word.
– T.J. Crowder
Dec 9 '15 at 16:23
there isevaloperator
– pery mimon
Jan 5 at 9:46
add a comment |
what they mean is no, you can't.
there is no way to get it done.
so it was possible you could do something like this
function create(obj, const)
// where obj is an object and const is a variable name
function const ()
const.prototype.myProperty = property_value;
// .. more prototype
return new const();
having a create function just like the one implemented in ECMAScript 5.
what they mean is no, you can't.
there is no way to get it done.
so it was possible you could do something like this
function create(obj, const)
// where obj is an object and const is a variable name
function const ()
const.prototype.myProperty = property_value;
// .. more prototype
return new const();
having a create function just like the one implemented in ECMAScript 5.
answered Nov 24 '12 at 5:29
AlfgaarAlfgaar
14117
14117
4
Beware: const is a keyword in ES6
– Tejas Manohar
Nov 17 '15 at 9:00
4
...and prior to that was a future reserved word.
– T.J. Crowder
Dec 9 '15 at 16:23
there isevaloperator
– pery mimon
Jan 5 at 9:46
add a comment |
4
Beware: const is a keyword in ES6
– Tejas Manohar
Nov 17 '15 at 9:00
4
...and prior to that was a future reserved word.
– T.J. Crowder
Dec 9 '15 at 16:23
there isevaloperator
– pery mimon
Jan 5 at 9:46
4
4
Beware: const is a keyword in ES6
– Tejas Manohar
Nov 17 '15 at 9:00
Beware: const is a keyword in ES6
– Tejas Manohar
Nov 17 '15 at 9:00
4
4
...and prior to that was a future reserved word.
– T.J. Crowder
Dec 9 '15 at 16:23
...and prior to that was a future reserved word.
– T.J. Crowder
Dec 9 '15 at 16:23
there is
eval operator– pery mimon
Jan 5 at 9:46
there is
eval operator– pery mimon
Jan 5 at 9:46
add a comment |
eval() did not work in my tests. But adding new JavaScript code to the DOM tree is possible. So here is a function that adds a new variable:
function createVariable(varName,varContent)
var scriptStr = "var "+varName+"= ""+varContent+"""
var node_scriptCode = document.createTextNode( scriptStr )
var node_script = document.createElement("script");
node_script.type = "text/javascript"
node_script.appendChild(node_scriptCode);
var node_head = document.getElementsByTagName("head")[0]
node_head.appendChild(node_script);
createVariable("dynamicVar", "some content")
console.log(dynamicVar)
2
small improvement, it is better to usevar node_head = document.getElementsByTagName("head")[0]instead of ID, as no one gives anid="head"to<head>:-)
– ddlab
Nov 9 '14 at 17:41
I do :) But thanks, now I can finally remove this `id="head" thing
– Axel Heider
May 4 '15 at 11:33
1
This just seems to be an overly complex way of creating a global variable?! (...and how does this answer the question?)
– MrWhite
Aug 23 '15 at 23:39
genius :) eval is the solution. Even if your code does not work
– pery mimon
Jan 4 at 18:27
add a comment |
eval() did not work in my tests. But adding new JavaScript code to the DOM tree is possible. So here is a function that adds a new variable:
function createVariable(varName,varContent)
var scriptStr = "var "+varName+"= ""+varContent+"""
var node_scriptCode = document.createTextNode( scriptStr )
var node_script = document.createElement("script");
node_script.type = "text/javascript"
node_script.appendChild(node_scriptCode);
var node_head = document.getElementsByTagName("head")[0]
node_head.appendChild(node_script);
createVariable("dynamicVar", "some content")
console.log(dynamicVar)
2
small improvement, it is better to usevar node_head = document.getElementsByTagName("head")[0]instead of ID, as no one gives anid="head"to<head>:-)
– ddlab
Nov 9 '14 at 17:41
I do :) But thanks, now I can finally remove this `id="head" thing
– Axel Heider
May 4 '15 at 11:33
1
This just seems to be an overly complex way of creating a global variable?! (...and how does this answer the question?)
– MrWhite
Aug 23 '15 at 23:39
genius :) eval is the solution. Even if your code does not work
– pery mimon
Jan 4 at 18:27
add a comment |
eval() did not work in my tests. But adding new JavaScript code to the DOM tree is possible. So here is a function that adds a new variable:
function createVariable(varName,varContent)
var scriptStr = "var "+varName+"= ""+varContent+"""
var node_scriptCode = document.createTextNode( scriptStr )
var node_script = document.createElement("script");
node_script.type = "text/javascript"
node_script.appendChild(node_scriptCode);
var node_head = document.getElementsByTagName("head")[0]
node_head.appendChild(node_script);
createVariable("dynamicVar", "some content")
console.log(dynamicVar)
eval() did not work in my tests. But adding new JavaScript code to the DOM tree is possible. So here is a function that adds a new variable:
function createVariable(varName,varContent)
var scriptStr = "var "+varName+"= ""+varContent+"""
var node_scriptCode = document.createTextNode( scriptStr )
var node_script = document.createElement("script");
node_script.type = "text/javascript"
node_script.appendChild(node_scriptCode);
var node_head = document.getElementsByTagName("head")[0]
node_head.appendChild(node_script);
createVariable("dynamicVar", "some content")
console.log(dynamicVar)
edited May 4 '15 at 11:37
answered Oct 5 '14 at 22:50
Axel HeiderAxel Heider
187110
187110
2
small improvement, it is better to usevar node_head = document.getElementsByTagName("head")[0]instead of ID, as no one gives anid="head"to<head>:-)
– ddlab
Nov 9 '14 at 17:41
I do :) But thanks, now I can finally remove this `id="head" thing
– Axel Heider
May 4 '15 at 11:33
1
This just seems to be an overly complex way of creating a global variable?! (...and how does this answer the question?)
– MrWhite
Aug 23 '15 at 23:39
genius :) eval is the solution. Even if your code does not work
– pery mimon
Jan 4 at 18:27
add a comment |
2
small improvement, it is better to usevar node_head = document.getElementsByTagName("head")[0]instead of ID, as no one gives anid="head"to<head>:-)
– ddlab
Nov 9 '14 at 17:41
I do :) But thanks, now I can finally remove this `id="head" thing
– Axel Heider
May 4 '15 at 11:33
1
This just seems to be an overly complex way of creating a global variable?! (...and how does this answer the question?)
– MrWhite
Aug 23 '15 at 23:39
genius :) eval is the solution. Even if your code does not work
– pery mimon
Jan 4 at 18:27
2
2
small improvement, it is better to use
var node_head = document.getElementsByTagName("head")[0] instead of ID, as no one gives an id="head" to <head> :-)– ddlab
Nov 9 '14 at 17:41
small improvement, it is better to use
var node_head = document.getElementsByTagName("head")[0] instead of ID, as no one gives an id="head" to <head> :-)– ddlab
Nov 9 '14 at 17:41
I do :) But thanks, now I can finally remove this `id="head" thing
– Axel Heider
May 4 '15 at 11:33
I do :) But thanks, now I can finally remove this `id="head" thing
– Axel Heider
May 4 '15 at 11:33
1
1
This just seems to be an overly complex way of creating a global variable?! (...and how does this answer the question?)
– MrWhite
Aug 23 '15 at 23:39
This just seems to be an overly complex way of creating a global variable?! (...and how does this answer the question?)
– MrWhite
Aug 23 '15 at 23:39
genius :) eval is the solution. Even if your code does not work
– pery mimon
Jan 4 at 18:27
genius :) eval is the solution. Even if your code does not work
– pery mimon
Jan 4 at 18:27
add a comment |
use Object is great too.
var a=123
var b=234
var temp = "a":a,"b":b
console.log(temp["a"],temp["b"]);
add a comment |
use Object is great too.
var a=123
var b=234
var temp = "a":a,"b":b
console.log(temp["a"],temp["b"]);
add a comment |
use Object is great too.
var a=123
var b=234
var temp = "a":a,"b":b
console.log(temp["a"],temp["b"]);
use Object is great too.
var a=123
var b=234
var temp = "a":a,"b":b
console.log(temp["a"],temp["b"]);
answered Mar 20 at 7:58
Steve JiangSteve Jiang
347313
347313
add a comment |
add a comment |
Although this have an accepted answer I would like to add an observation:
In ES6 using let doesn't work:
/*this is NOT working*/
let t = "skyBlue",
m = "gold",
b = "tomato";
let color = window["b"];
console.log(color);However using var works
/*this IS working*/
var t = "skyBlue",
m = "gold",
b = "tomato";
let color = window["b"];
console.log(color);I hope this may be useful to some.
1
same applies toconst
– user4244405
Apr 19 at 8:26
add a comment |
Although this have an accepted answer I would like to add an observation:
In ES6 using let doesn't work:
/*this is NOT working*/
let t = "skyBlue",
m = "gold",
b = "tomato";
let color = window["b"];
console.log(color);However using var works
/*this IS working*/
var t = "skyBlue",
m = "gold",
b = "tomato";
let color = window["b"];
console.log(color);I hope this may be useful to some.
1
same applies toconst
– user4244405
Apr 19 at 8:26
add a comment |
Although this have an accepted answer I would like to add an observation:
In ES6 using let doesn't work:
/*this is NOT working*/
let t = "skyBlue",
m = "gold",
b = "tomato";
let color = window["b"];
console.log(color);However using var works
/*this IS working*/
var t = "skyBlue",
m = "gold",
b = "tomato";
let color = window["b"];
console.log(color);I hope this may be useful to some.
Although this have an accepted answer I would like to add an observation:
In ES6 using let doesn't work:
/*this is NOT working*/
let t = "skyBlue",
m = "gold",
b = "tomato";
let color = window["b"];
console.log(color);However using var works
/*this IS working*/
var t = "skyBlue",
m = "gold",
b = "tomato";
let color = window["b"];
console.log(color);I hope this may be useful to some.
/*this is NOT working*/
let t = "skyBlue",
m = "gold",
b = "tomato";
let color = window["b"];
console.log(color);/*this is NOT working*/
let t = "skyBlue",
m = "gold",
b = "tomato";
let color = window["b"];
console.log(color);/*this IS working*/
var t = "skyBlue",
m = "gold",
b = "tomato";
let color = window["b"];
console.log(color);/*this IS working*/
var t = "skyBlue",
m = "gold",
b = "tomato";
let color = window["b"];
console.log(color);answered Mar 23 at 9:36
enxanetaenxaneta
11.4k2821
11.4k2821
1
same applies toconst
– user4244405
Apr 19 at 8:26
add a comment |
1
same applies toconst
– user4244405
Apr 19 at 8:26
1
1
same applies to
const– user4244405
Apr 19 at 8:26
same applies to
const– user4244405
Apr 19 at 8:26
add a comment |
protected by Community♦ Apr 11 '18 at 16:47
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
2
Possible dupe of stackoverflow.com/questions/724857/…, and stackoverflow.com/questions/1664282/…, but the accepted answer here better, IMO.
– goodeye
May 22 '13 at 22:41