const EleList = [1,2,3]
name = 'Ele'
const render = function(type){
window[type + 'List'].forEach(function(value){
console.log("LOL")
render('Ele')
What am i supposed to replace the window[name + 'List'] with to call an array using strings.
const or let variables are not added to the global window object.
Replacing const with var should solve your problem.
var EleList = [1,2,3]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
Global constants do not become properties of the window object, unlike var variables.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
Just like const the let does not create properties of the window object when declared globally (in the top-most scope).
Related
Is there an option to get a reference to the whole script variables?
lets assume this code:
const a=n=>n+1,
b={};
let c=3
I wonder if I can access all variables by one reference, like this vars:
vars.b //{}
vars[varName]
so that I'll be able to pass it to other sub modules easily instead of creating a manualy associative array with the variables of the script
It is possible only to some limit.
There is globalThis variable acting as a container for all top-level variables.
And also in every function arguments variable is available holding everything passed to function in the current call.
I'm not aware of anything similar for function-/block-scope variables
I think you can assign those variables to a JSON object and then export the JSON object as follows so that you can reference all the variables in other file.
// scripts.js file
let a = n => n+1;
let b = {};
let c = 3;
module.exports = { a, b, c };
// index.js file
const scripts = require('./scripts');
console.log(scripts.a(4));
console.log(scripts.b);
console.log(scripts.c);
No, there's no way to programatically get access to the environment record of a given function/scope/closure. To do something like this, the best way would be to define the variables as part of an object or Map in the first place. Instead of
const a=n=>n+1,
b={};
let c=3
do
const theNamespace = {
a: n=>n+1,
b: {},
c: 3
};
and pass theNamespace around.
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
look at this example:
const a = 5
module.exports.a = a;
let b = "foo"
module.exporta.b = b
if we export this variables . in everywhere a variable is const and b variable is let .what about this example :
module.exports.c = "bar"
what is this? a var type? let? const? I mean javascript engine treat this to what? I am getting wrong definition or behavior of javascript or this is a correct question that came to my mind?
const and let are for defining variables. Things in module.exports are properties of an object (that object being module.exports), and so they are controlled by their property descriptors. Whether or not the value is mutable is controlled by the writable descriptor field. It no longer has a scope of its own, it can be accessed wherever its parent can. You can't really think of them like a let or const.
Since in Javascript, arguments are passed by value, in this:
let b = "foo"
module.exports.b = b
After this code is executed, module.exports.b has nothing to do with the variable b. It's not a let, or a const it's just a property of module.exports. You could change the value of b and it would have no effect on module.exports.b.
When you're doing module.exports.a = 'a', you're not exporting a variable itself, you're exporting a binding.
Then if when importing you assigng it to const like const {a} = require('./a'), it will be const, if you import it assigning to let {a} = require('./a'), it will be let.
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.
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.