Javascript create variable from its name - javascript

In PHP we can do this:
$variable = "name_of_variable";
$this->{$variable} = "somevalue";
how to do this in javascript?
where use case should look like:
function Apple(){
var name = "variable_name";
this.(name) = "value";
}
console.log(new Apple());
to output
[Apple: {variable_name:"value"}]

try:
this[name] = "value";
All objects can use dot and array notation for variable access.
Also note, this will allow you to create name value pairs that are inaccessible via dot notation:
var foo = {};
foo['bar-baz'] = 'fizzbuzz';
alert(foo.bar-baz); //this will not work because `-` is subtraction
alert(foo['bar-baz']); //this will work fine
If you are creating a new object literal, you can use string literals for the names for values with special characters:
var foo = {'bar-baz':'fizzbuzz'};
But you will not be able to use variables as the key within an object literal because they are interpreted as the name to use:
var foo = 'fizz';
var bar = { foo:'buzz' }
alert( bar.fizz ); //this will not work because `foo` was the key provided
alert( bar.foo ); //alerts 'buzz'
Because other answerers are mentioning eval, I will explain a case where eval could be useful.
Warning! Code using eval is evil, proceed with caution.
If you need to use a variable with a dynamic name, and that variable does not exist on another object.
It's important to know that calling var foo in the global context attaches the new variable to the global object (typically window). In a closure, however, the variable created by var foo exists only within the context of the closure, and is not attached to any particular object.
If you need a dynamic variable name within a closure it is better to use a container object:
var container = {};
container[foo] = 'bar';
So with that all being said, if a dynamic variable name is required and a container object is not able to be used, eval can be used to create/access/modify a dynamic variable name.
var evalString = ['var', variableName, '=', String.quote(variableValue), ';'].join(' ')
eval( evalString );

You can use square bracket notation in Javascript:
variable = "name_of_variable";
window[variable] = "somevalue";
You can do this with any object in Javascript.

var name = "var_name";
var obj = {};
obj[name] = 'value';
alert(obj.var_name);

I suggest using associative arrays to do whatever you're trying to do as they are significantly cleaner and easier to debug.
However if you really insist, you can use eval() to accomplish this:
variable = "name_of_variable";
eval(variable + " = \"somevalue\""); // this will work, but please do not do it
alert(name_of_variable);
EDIT: It his just come to my attention that a significantly easier (and better) way of doing this is by simply accessing the window object:
window[variable] = "somevalue";
http://jsfiddle.net/WJCrB/

window['name_of_variable'] = 'somevalue';
or
eval('var ' + variable_name + ' = ' + variable_name + ';');
Beyond that, don't do this. Variable variables are NEVER a good idea and make it nearly impossible to debug problems when (invariably) things break.

Related

Get element's ID and set it as variable

I have a button:
<button class="btn btn-info continue">
<i class="ace-icon fa fa-check bigger-110"></i>
Continue
</button>
Onclick:
$(".continue").click(function(e) {
currForm = $(this).parents('form');
e.preventDefault();
});
I can get the id pretty easily: currForm.attr('id');, but can I set the value of this id as a variable.
Something like php's variable variables:
$a = 'hello';
$$a = 'world';
echo $hello;
Edit: I don't want to change element's id. I want to get this ID and use it as a name for a javascript variable.
For example, the element I provided above is in a form that has ID='example_id'. currForm.attr('id') will give me example_id and I want to set a variable example_id and assign a value to it.
var example_id = 'some value';
Here's 3 options for you.
eval (not recommended)
You can use the Javascript function eval to achieve what you want. But be aware, this is not recommended (I emphasized it twice, hope you understood!).
Don't use eval needlessly!
eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, third party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.
It would be used like that :
eval('var ' + varName + ' = "something";');
Window object notation (Better than eval, still not really recommended)
This method consists of using the object notation provided by JavaScript on the global window object. This is polluting the global window scope and can be overridden by other JS files, which is bad. If you want to know more about that subject, this is a good question: Storing a variable in the JavaScript 'window' object is a proper way to use that object?.
To use this technic, you would do something like:
window[varName] = something;
alert(window[varName]);
Using an object (recommended)
The best solution would be to create your own variable scope. For instance, you could create on the global scope a variable and assign an object to it. You can then use the object notation to create your dynamic variables. It works the same way as the window does :
var globalScope = {};
function awesome(){
var localScope = {};
globalScope[varName] = 'something';
localScope[varName] = 'else';
notSoAwesome();
}
function notSoAwesome(){
alert(globalScope[varName]); // 'something';
alert(localScope[varName]); // undefined
}
You can do it using javascript object:
var currForm = $(this).parents('form');//form id="hello"
var obj = {};
obj[currForm.attr('id')] = 30;
console.log(obj.hello)
You can use and object to store your variables in:
var variables = {};
to add a variable just type:
variables[name] = value;
and to access the value:
variables[name]
Check it out here: jsFiddle
Button 2 reads the value of variables[formid] and button 1 sets formid to submitted
Try one of the following:
$(this).attr(example_id, "value")
Or
window[ currForm.attr(id)] = 12;
Or
window[ this.id ] = 12;
Your best option for archieving what you really want is using eval(), like this:
eval("var " + currForm.attr('id');
Check this link ->
Dynamic Variables in Javascript
Use eval (but not recommended):
var id = 'that_id';
eval(id+" = 'other id';");
alert(that_id); // results: 'other id'

Javascript split() not working! completely stumped

filename = "file_1";
name = filename.split('_');
test1 = name[0];
test2 = name[1];
console.log(test1);
console.log(test2);
Expected Result:
file
1
Actual Result:
f
i
http://jsfiddle.net/j667q/1/
I must be doing something wrong, but can't for the life of me work out what.
I have tried:
Using different quotes ' and "
Defining filename and name before using (filename = '';
name = [];)
Spliting using a different character ('-')
Define the array variable first:
var name = [];
DEMO http://jsfiddle.net/j667q/5/
Why this works?
Update for more clarification based on comments:
Although name is not a reserved word, it's a global property of window (eg. window.name and name mean the same), var name; will define a new variable called name which is in another scope and avoids the conflict.
JavaScript Reserved words: http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Words
The problem is, something to do with global conflicts the global object has a property called name and is somehow conflicting with your code.
rename it http://jsfiddle.net/j667q/3/
you could do var name = ...split... if you don't want to rename it
Yeah, also note, you should ALWAYS declare variables with var there is no reason not to, if you want a global property do window.someName = something;
Declare the variables as var to scope them properly
var filename = "file_1";
var names = filename.split('_');
test1 = name[0];
test2 = name[1];
console.log(test1);
console.log(test2);
name is a js global property. so try not to use it. hope that will help
you have to declare both variables like this.
var filename = "file_1";
var name = filename.split('_');
check out the updated JSFIDDLE (http://jsfiddle.net/prakashcbe/j667q/17/)
Try this...
Other answers all are correct. I don't know your mistake. Anyway, try this as well
[http://jsfiddle.net/puvanarajan/Nytgh/][1]

Javascript: Naming arrays programmatically

Is it possible to create a new Array, giving it the name of the content of a variable?
For example something like this:
var nameofarray = "array_name";
var ¿nameofarray? = new Array();
So that ¿nameofarray? gets the value of "array_name"?
Assuming you are in global scope (called window) so:
var nameofarray = "array_name";
window[nameofarray] = new Array();
Otherwise it's only posible on objects:
function a() {
var nameofarray = "array_name";
var obj = {};
obj[nameofarray] = new Array();
}
You can also use eval. Which is used for evaluating a string to JavaScript code:
eval('var '+ nameofarray+'=new Array()');
This will work in local scopes as well, but I hardly ever recorment it to anyone.
You would maybe like to read: http://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/
In PHP and other languages, they are called variable variables. This might help: Javascript "Variable Variables": how to assign variable based on another variable?
If nameofarray is declared in the global scope, you can use the window object:
window[nameofarray] = []; // Use an array literal instead also
^^^^^^^^^^^^^^^^^^^
But you really shouldn't be doing this.

Access variable from code run in "eval" in Javascript

I know using eval is not at all recommended and I have read this link too. Set Variable inside Eval (JavaScript)
However, this is what I want to do. Lets say we have some code in a textbox. So I have to take that text, and then find out all the global variables, functions and objects in that code.
My idea was to wrap the code in a namespace, eval it and then iterate through the properties of the namespace to get the results. However, even though the eval runs successfully, I can't access the variable defined there. Is there a better solution or some other way to get this working.
http://jsfiddle.net/DbrEF/2/ - This is the Fiddle here.
The "var code" could actually be arbitrary code. I know its unsafe to do it but I need it for a different context.
Thanks
In 2015, creating a Function object is your best bet here, rather than using eval:
new Function('arg1', 'arg2', 'return arg1 + arg2')(3,4) // returns 7
You might have better luck using a Javascript parser, like the one used by JSHint/JSLint
here's a demo on safely using eval using "use strict"
window.onload = function(){
'use strict';
//use strict forces to run code in "strict mode"
//use strict prevents eval from
//contaminating the immediate scope
//let's test with "foo"
var foo = 'lol';
//now code has "foo" but using "use strict"
//makes code in eval stay in eval
//note that at the last of the code, foo is "returned"
var code = 'var foo = {name: "Spock",greeting: function() {return "Hello " + foo.name;}}; foo';
//store eval'ed code in evalO
var evalstore = eval(code);
console.log(evalstore); //code in eval stays in here, which is "inner foo"
console.log(foo); //"outer foo" is unharmed and daisy fresh
}​;
so whatever code you have, contain it in a function which will serve as your namespace. then have that function returned to the outside world stored as a variable. this demo shows how it can be constructed, however, works only if code is in object literal notation.
window.onload = function() {
'use strict';
var ns = 'lol';
//code must be an object literal
var code = '{name: "Spock",greeting: function(){return "Hello " + foo.name;}}';
//store in a constructor to be returned
var constructorString = 'var ns = function(){return ' + code + '}; ns';
var evalNs = eval(constructorString); //type function/constructor
var evalObj = new evalNs() //object instance
console.log(evalNs); //constructor
console.log(evalObj); //the namespaced object
console.log(ns); //outer "ns" preserved
};​
​
Probably not what exactly OP was looking for but another option is to use outside variables to store values generated inside eval, as in:
var value;
var code = 'var foo = 42';
code = code.replace('var foo', 'value');
eval(code);
value // returns 42;

Variable variables in JavaScript

according to my knowledge, this feature already exists in PHP. lets look at the following php code:
$color = 'red';
$$color = 'dark';
description of the feature:
Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically.A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, red, can be used as the name of a variable.At this point two variables have been defined and stored in the PHP symbol tree: $color with contents "red" and $red with contents "dark".
my Question
can this be done in java Script?
Three different techniques come to mind, each with its warnings and (except the second one) uses:
1) You can declare a new variable in JavaScript anywhere in the code using the var keyword:
var $color = 'red';
The variable is actually defined throughout the scope in which the var occurs, even above the var statement — that is, these two functions are identical even though they look slightly different:
function foo() {
doSomething();
var x = 5;
x += doSomethingElse();
return x;
}
function foo() {
var x;
doSomething();
x = 5;
x += doSomethingElse();
return x;
}
This is because all vars take effect when the context for the function is created, not where they appear in the code. More: Poor, misunderstood var
2) If you just assign to a free symbol that's never been declared anywhere, you'll create an implicit global variable (not one constrained to the current scope), which is generally a bad idea. More: The Horror of Implicit Globals
3) Another thing you can do is have an object which is a container for various variables you want to track. You can create new properties on the object just by assigning them:
var data = {}; // A blank object
data.foo = "bar"; // Now `data` has a `foo` property
This technique is particularly handy when you need to track data that your script is completely unaware of, for instance based on user input, because you can use either dotted notation and a literal as above (data.foo), or you can use bracketed notation and a string (data["foo"]). In the latter case, the string can be the result of any expression, so all of these create a foo property on data:
// Dotted notation with a literal
data.foo = 42;
// Bracketed notation with a literal string
data["foo"] = 42;
// Bracketed notation with a string coming from a variable
s = "foo";
data[s] = 42;
// Bracketed notation with a string coming from an expression
s = "o";
data["f" + s + s] = 42;
var color = 'red';
window[color] = 'dark';
console.log(color, red);

Categories

Resources