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.
Related
I would like to declare a variable whose name is the content of another other variable. It is possible ?
I tried this :
var "x" + "y" = 1;
to declare this :
var xy = 1;
But this throw an error : Uncaught SyntaxError: Unexpected string
The only way (AFAIK) to create local variables with dynamic names is with eval(). This is not a great solution, because of performance concerns. You can also create global variables with dynamic names using the global object.
eval(`var ${varName} = 123;`);
globalThis[varName] = 123;
However, creating variables with dynamic names is not a common practice. Most likely what you need is a Map.
const varName = "varName", otherVarName = "otherVarName";
const map = new Map();
map.set(varName, 123);
map.set(otherVarName, 456);
console.log(map.get(varName), map.get(otherVarName));
In JavaScript somehow you can create dynamic variables using eval function or window object:
eval('var xy="evalTest";');
alert(xy);
window["xy"] = "windowTest";
alert(window["xy"]);
Another possible solution is to create a json with all your global variables.
//create an empty json (at the top of your javascript file)
const globalVariables = {};
//add variable and value to your json
globalVariables["x"+"y"] = 1;
//access value from json
console.log(globalVariables["xy"]); // this function will log 1 to the console
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]
I need to reference my object as a string but I am having issues.
ideally I would like this to work ['mystring'].myproperty; but obviously this wont work.
Is there another way besides the options below?
// auto generated ecample/////////////
var mystring = {
myproperty :'test'
}
/////////////////////////////////////
var optionA =mystring.myproperty; // works
var optionB = window['mystring'].myproperty; //gives issues
var optionC = eval('mystring').myproperty; //gives issues
var optionD = ['mystring'].myproperty; // wont work
If your variables are defined on a global scope, the following works
window[ mystring.myproperty ].data
If you are in a function's scope, things get a lot harder. Easiest way then is to define your objects in a specific namespace on window and retrieve the objects similar to the above code.
Basically i'm having trouble with something that i'm sure is super duper simple but I just don't know what to call it and therefore I am having trouble searching for an answer. :(
Basically, say I've declared an object, i.e var meow = {}; and then i decide to create an object within that by doing something like meow.cutekitten = {}; this is all straight forward and i end up with an object called cutekitten within that.
My issue is, what if I've declared cutekitten as a variable and i want to use the contents of that variable as the name of this new object rather than the variable name?
var propertyName = "cutekitten";
var meow = {};
meow[ propertyName ] = {};
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.