quick question about JavaScript variables - javascript

Not sure what to search for here, so apologies if I'm repeating another question.
I'm wondering if there are any issues that I'm not aware of with using the following syntax in JavaScript:
var a = {};
var b = a.niceCoat = {};
Seems handy, but I just want to make sure...

That is perfectly fine, because a was declared previously. The expressions will be evaluated as
var a = {};
var b = (a.niceCoat = {});
I.e. it first assigns a new empty object to a.niceCoat and the result (the result of an assignment is the assigned value) to b.
But be aware of something like
var a = b = 'c';
which, again, is evaluated as
var a = (b = 'c');
Only a will be in local scope, b would be global. If you want b to be local too, you have to declare it beforehand: var b;. Something like var a = var b = .... does not work (not valid syntax).
Slightly off topic:
This method is indeed handy. Imaging you have an object of objects, something like:
var map = {
foo: {},
bar: {}
};
and you want to get the object for a certain key or create a new one if the key does not exists. Normally one would probably do:
var obj = map[key];
if(!obj) { // works because if the key is set, it is an object
obj = {}; // which evals to true
map[key] = obj;
}
// now work with obj
With the above method, this can be shortened to
var obj = map[key];
if(!obj) {
map[key] = obj = {};
}
And we can make it even shorter with the logical OR operator (||):
var obj = map[key] || (map[key] = {});
(though it might be less readable).

You can do that. a.niceCoat = {} will be evaluated first, which assigns the object to the property and also has the object as result, which you then can assign to the variable.
You should however be aware that b and a.niceCoat are now referencing the same object, so if you put anything in the object it will show up for both the variable and the property:
var a = {};
var b = a.niceCoat = {};
b.x = 42;
alert(a.niceCoat.x); // shows 42

There no issue with that. It's the same as:
var b = (a.niceCoat = {});
Which is the same as:
a.niceCoat = {};
var b = a.niceCoat; // Now b and a.niceCoat are the same object
Just be careful with declaring entirely new variables with it like:
var i = j = 0;
Which is the same as:
j = 0;
var i = j;
Notice how j is not declared with the var keyword.

this is how you create an empty object in javascript. nothing wrong with it.

Yep, absolutely valid.
E.g.
var a = {};
var b = a.niceCoat = {};
a.foo = function() { alert('foo!'); };
a.foo(); // shows the alert

Related

javascript var a1 and call with alert(a+1) string and number [duplicate]

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?
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
console.log(name);
name = this['a']; // === 1
console.log(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).
eval is one option.
var a = 1;
var name = 'a';
document.write(eval(name)); // 1
Warning: Note that using the eval() function is not recommended if you don't know what you are doing, since it brings multiple security issues. Use something else unless absolutely necessary. See the MDN page for eval for more info.
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.
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);
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.
a = 'varname';
str = a+' = '+'123';
eval(str)
alert(varname);
Try this...
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"]);
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']);
2019
TL;DR
eval operator can run string expression in the context it called and return variables from that context;
literal object theoretically can do that by write:{[varName]}, but it blocked by definition.
So I come across this question and everyone here just play around without bringing a real solution. but #Axel Heider has a good approaching.
The solution is eval.
almost most forgotten operator. ( think most one is with() )
eval operator can dynamically run expression in the context it called. and return the result of that expression. we can use that to dynamically return a variable's value in function's 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 }`
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);
This is an alternative for those who need to export a dynamically named variable
export {
[someVariable]: 'some value',
[anotherVariable]: 'another value',
}
// then.... import from another file like this:
import * as vars from './some-file'
Another alternative is to simply create an object whose keys are named dynamically
const vars = { [someVariable]: 1, [otherVariable]: 2 };
// consume it like this
vars[someVariable];
use Object is great too.
var a=123
var b=234
var temp = {"a":a,"b":b}
console.log(temp["a"],temp["b"]);
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 will do exactly what you done in php:
var a = 1;
var b = 2;
var ccc = 3;
var name = 'a';
console.log( window[name] ); // 1
Simplest solution : Create an array of objects that every object has two field (variableName,variableValue)
let allVariables = [];
for (let i = 0; i < 5; i++)
allVariables.push({ variableName: 'variable' + i, variableValue: i * 10 });
for (let i = 0; i < allVariables.length; i++)
console.log(allVariables[i].variableName + ' is ' + allVariables[i].variableValue);
OutPut :
variable0 is 0
variable1 is 10
variable2 is 20
variable3 is 30
variable4 is 40
console.log(allVariables) json :
[
{
"variableName": "variable0",
"variableValue": 0
},
{
"variableName": "variable1",
"variableValue": 10
},
{
"variableName": "variable2",
"variableValue": 20
},
{
"variableName": "variable3",
"variableValue": 30
},
{
"variableName": "variable4",
"variableValue": 40
}
]
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.
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)
Here's pure javascript solution which is not dependant on the global this of the runtime environment. Simple to achieve using object destructuring.
const dynamicVar = (nameValue, value) => {
const dynamicVarObj = {
[nameValue]: value
}
return dynamicVarObj;
}
const nameToUse = "myVar";
const value = 55;
const { myVar } = dynamicVar(nameToUse, value);
console.log(myVar); // prints 55
It is always better to use create a namespace and declare a variable in it instead of adding it to the global object. We can also create a function to get and set the value
See the below code snippet:
//creating a namespace in which all the variables will be defined.
var myObjects={};
//function that will set the name property in the myObjects namespace
function setName(val){
myObjects.Name=val;
}
//function that will return the name property in the myObjects namespace
function getName(){
return myObjects.Name;
}
//now we can use it like:
setName("kevin");
var x = getName();
var y = x;
console.log(y) //"kevin"
var z = "y";
console.log(z); //"y"
console.log(eval(z)); //"kevin"
In this similar way, we can declare and use multiple variables. Although this will increase the line of code but the code will be more robust and less error-prone.

Having problems passing template literals in function [duplicate]

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?
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
console.log(name);
name = this['a']; // === 1
console.log(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).
eval is one option.
var a = 1;
var name = 'a';
document.write(eval(name)); // 1
Warning: Note that using the eval() function is not recommended if you don't know what you are doing, since it brings multiple security issues. Use something else unless absolutely necessary. See the MDN page for eval for more info.
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.
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);
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.
a = 'varname';
str = a+' = '+'123';
eval(str)
alert(varname);
Try this...
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"]);
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']);
2019
TL;DR
eval operator can run string expression in the context it called and return variables from that context;
literal object theoretically can do that by write:{[varName]}, but it blocked by definition.
So I come across this question and everyone here just play around without bringing a real solution. but #Axel Heider has a good approaching.
The solution is eval.
almost most forgotten operator. ( think most one is with() )
eval operator can dynamically run expression in the context it called. and return the result of that expression. we can use that to dynamically return a variable's value in function's 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 }`
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);
This is an alternative for those who need to export a dynamically named variable
export {
[someVariable]: 'some value',
[anotherVariable]: 'another value',
}
// then.... import from another file like this:
import * as vars from './some-file'
Another alternative is to simply create an object whose keys are named dynamically
const vars = { [someVariable]: 1, [otherVariable]: 2 };
// consume it like this
vars[someVariable];
use Object is great too.
var a=123
var b=234
var temp = {"a":a,"b":b}
console.log(temp["a"],temp["b"]);
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 will do exactly what you done in php:
var a = 1;
var b = 2;
var ccc = 3;
var name = 'a';
console.log( window[name] ); // 1
Simplest solution : Create an array of objects that every object has two field (variableName,variableValue)
let allVariables = [];
for (let i = 0; i < 5; i++)
allVariables.push({ variableName: 'variable' + i, variableValue: i * 10 });
for (let i = 0; i < allVariables.length; i++)
console.log(allVariables[i].variableName + ' is ' + allVariables[i].variableValue);
OutPut :
variable0 is 0
variable1 is 10
variable2 is 20
variable3 is 30
variable4 is 40
console.log(allVariables) json :
[
{
"variableName": "variable0",
"variableValue": 0
},
{
"variableName": "variable1",
"variableValue": 10
},
{
"variableName": "variable2",
"variableValue": 20
},
{
"variableName": "variable3",
"variableValue": 30
},
{
"variableName": "variable4",
"variableValue": 40
}
]
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.
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)
Here's pure javascript solution which is not dependant on the global this of the runtime environment. Simple to achieve using object destructuring.
const dynamicVar = (nameValue, value) => {
const dynamicVarObj = {
[nameValue]: value
}
return dynamicVarObj;
}
const nameToUse = "myVar";
const value = 55;
const { myVar } = dynamicVar(nameToUse, value);
console.log(myVar); // prints 55
It is always better to use create a namespace and declare a variable in it instead of adding it to the global object. We can also create a function to get and set the value
See the below code snippet:
//creating a namespace in which all the variables will be defined.
var myObjects={};
//function that will set the name property in the myObjects namespace
function setName(val){
myObjects.Name=val;
}
//function that will return the name property in the myObjects namespace
function getName(){
return myObjects.Name;
}
//now we can use it like:
setName("kevin");
var x = getName();
var y = x;
console.log(y) //"kevin"
var z = "y";
console.log(z); //"y"
console.log(eval(z)); //"kevin"
In this similar way, we can declare and use multiple variables. Although this will increase the line of code but the code will be more robust and less error-prone.

How to create a dynamic var in Javascript [duplicate]

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?
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
console.log(name);
name = this['a']; // === 1
console.log(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).
eval is one option.
var a = 1;
var name = 'a';
document.write(eval(name)); // 1
Warning: Note that using the eval() function is not recommended if you don't know what you are doing, since it brings multiple security issues. Use something else unless absolutely necessary. See the MDN page for eval for more info.
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.
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);
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.
a = 'varname';
str = a+' = '+'123';
eval(str)
alert(varname);
Try this...
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"]);
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']);
2019
TL;DR
eval operator can run string expression in the context it called and return variables from that context;
literal object theoretically can do that by write:{[varName]}, but it blocked by definition.
So I come across this question and everyone here just play around without bringing a real solution. but #Axel Heider has a good approaching.
The solution is eval.
almost most forgotten operator. ( think most one is with() )
eval operator can dynamically run expression in the context it called. and return the result of that expression. we can use that to dynamically return a variable's value in function's 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 }`
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);
This is an alternative for those who need to export a dynamically named variable
export {
[someVariable]: 'some value',
[anotherVariable]: 'another value',
}
// then.... import from another file like this:
import * as vars from './some-file'
Another alternative is to simply create an object whose keys are named dynamically
const vars = { [someVariable]: 1, [otherVariable]: 2 };
// consume it like this
vars[someVariable];
use Object is great too.
var a=123
var b=234
var temp = {"a":a,"b":b}
console.log(temp["a"],temp["b"]);
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 will do exactly what you done in php:
var a = 1;
var b = 2;
var ccc = 3;
var name = 'a';
console.log( window[name] ); // 1
Simplest solution : Create an array of objects that every object has two field (variableName,variableValue)
let allVariables = [];
for (let i = 0; i < 5; i++)
allVariables.push({ variableName: 'variable' + i, variableValue: i * 10 });
for (let i = 0; i < allVariables.length; i++)
console.log(allVariables[i].variableName + ' is ' + allVariables[i].variableValue);
OutPut :
variable0 is 0
variable1 is 10
variable2 is 20
variable3 is 30
variable4 is 40
console.log(allVariables) json :
[
{
"variableName": "variable0",
"variableValue": 0
},
{
"variableName": "variable1",
"variableValue": 10
},
{
"variableName": "variable2",
"variableValue": 20
},
{
"variableName": "variable3",
"variableValue": 30
},
{
"variableName": "variable4",
"variableValue": 40
}
]
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.
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)
Here's pure javascript solution which is not dependant on the global this of the runtime environment. Simple to achieve using object destructuring.
const dynamicVar = (nameValue, value) => {
const dynamicVarObj = {
[nameValue]: value
}
return dynamicVarObj;
}
const nameToUse = "myVar";
const value = 55;
const { myVar } = dynamicVar(nameToUse, value);
console.log(myVar); // prints 55
It is always better to use create a namespace and declare a variable in it instead of adding it to the global object. We can also create a function to get and set the value
See the below code snippet:
//creating a namespace in which all the variables will be defined.
var myObjects={};
//function that will set the name property in the myObjects namespace
function setName(val){
myObjects.Name=val;
}
//function that will return the name property in the myObjects namespace
function getName(){
return myObjects.Name;
}
//now we can use it like:
setName("kevin");
var x = getName();
var y = x;
console.log(y) //"kevin"
var z = "y";
console.log(z); //"y"
console.log(eval(z)); //"kevin"
In this similar way, we can declare and use multiple variables. Although this will increase the line of code but the code will be more robust and less error-prone.

Is it necessary to create nested jSON objects before using it?

I think I've seen how to create a JSON object without first preparing it. This is how i prepare it:
obj = {
0:{
type:{}
},
1:{},
2:{}
};
Now I think I can insert a value like: obj.0.type = "type0"; But I'd like to create it while using it: obj['0']['type'] = "Type0";.
Is it possible, or do I need to prepare it? I'd like to create it "on the fly"!
EDIT
I'd like to create JS object "On the fly".
var obj = {};
obj.test = "test"; //One "layer" works fine.
obj.test.test = "test" //Two "layers" do not work... why?
obj = {
0:{
type:{}
},
1:{},
2:{}
};
Now i think i can insert value like: obj.0.type = "type0";
I guess you mean "assign" a value, not "insert". Anyway, no, you can't, at least not this way, because obj.0 is invalid syntax.
But I'd like to create it while using it: obj['0']['type'] = "Type0";
That's fine. But you need to understand you are overwriting the existing value of obj[0][type], which is an empty object ({}), with the string Type0. To put it another way, there is no requirement to provide an initialized value for a property such as type in order to assign to it. So the following would have worked equally well:
obj = {
0:{},
1:{},
2:{}
};
Now let's consider your second case:
var obj = {};
obj.test = "test"; //One "layer" works fine.
obj.test.test = "test" //Two "layers" do not work... why?
Think closely about what is happening. You are creating an empty obj. You can assign to any property on that object, without initializing that property. That is why the assignment to obj.test works. Then in your second assignment, you are attempting to set the test property of obj.test, which you just set to the string "test". Actually, this will work--because strings are objects that you can set properties on. But that's probably not what you want to do. You probably mean to say the previous, string value of obj.test is to be replaced by an object with its own property "test". To do that, you could either say
obj.test = { test: "test" };
Or
obj.test = {};
obj.test.test = "test";
You are creating a plain object in JavaScript and you need to define any internal attribute before using it.
So if you want to set to "Type0" an attribute type, inside an attribute 0 of an object obj, you cannot simply:
obj['0']['type'] = "Type0";
You get a "reference error". You need to initialize the object before using it:
var obj = {
0: {
type: ""
}
};
obj['0']['type'] = "Type0";
console.log(obj['0']['type']);
You could create your own function that takes key as string and value and creates and returns nested object. I used . as separator for object keys.
function create(key, value) {
var obj = {};
var ar = key.split('.');
ar.reduce(function(a, b, i) {
return (i != (ar.length - 1)) ? a[b] = {} : a[b] = value
}, obj)
return obj;
}
console.log(create('0.type', 'type0'))
console.log(create('lorem.ipsum.123', 'someValue'))
Is it necessary to create nested objects before using it?
Yes it is, at least the parent object must exist.
Example:
var object = {};
// need to assign object[0]['prop'] = 42;
create the first property with default
object[0] = object[0] || {};
then assign value
object[0]['prop'] = 42;
var object = {};
object[0] = object[0] || {};
object[0]['prop'] = 42;
console.log(object);
Create object with property names as array
function setValue(object, keys, value) {
var last = keys.pop();
keys.reduce(function (o, k) {
return o[k] = o[k] || {};
}, object)[last] = value;
}
var object = {};
setValue(object, [0, 'prop'], 42);
console.log(object);

JavaScript Object/Array access question

Set an object, with some data.
var blah = {};
blah._a = {};
blah._a._something = '123';
Then wish to try and access, how would I go about doing this correctly?
var anItem = 'a';
console.log(blah._[anItem]);
console.log(blah._[anItem]._something);
The bracket notation should look like this:
var anItem = 'a';
console.log(_glw['_'+anItem]);
console.log(_glw['_'+anItem]._something);
You can test it here (note that I replaced _glw with blah in the demo to match the original object).
Not sure I understand the question, but here are some basics.
var foo = {};
// These two statements do the same thing
foo.bar = 'a';
foo['bar'] = 'a';
// So if you need to dynamically access a property
var property = 'bar';
console.log(foo[property]);
var obj = {};
obj.anotherObj = {};
obj.anotherObj._property = 1;
var item = '_property';
// the following lines produces the same output
console.log(obj.anotherObj[item]);
console.log(obj.anotherObj['_property']);
console.log(obj.anotherObj._property);

Categories

Resources