Javascript - set a variable using concatenation of strings [duplicate] - javascript

This question already has answers here:
Use dynamic variable names in JavaScript
(19 answers)
Closed 9 years ago.
Is it possible to set a variable by concatenating two strings together to form the name?
If at all possible I'd like to determine what variable to set based on the class names of the objects that the user clicks. I know I can hard code a bunch of if/else if statements, but it would be really cool if I could reference the variables indirectly. I was thinking something like this:
var owner_read;
var group_read;
function setVariableIndirectly(object){
var second = object.className; // returns "read"
var first = object.parentElement.className; // returns "group"
first + "_" + second = "set this as the new variable";
}
Is there any way of doing this??
EDIT:
Here's the html that the data is coming in from.
<p class="owner">
<span class="read" onclick="permissionClick(this)">r</span>
<span class="write" onclick="permissionClick(this)">w</span>
<span class="execute" onclick="permissionClick(this)">x</span>
</p>

This is possible but you have to be wary of context and scope.
1. To set variable with global scope in browser environment:
window[str1 + str2] = value
2. To set variable with global scope in node environment:
global[str1 + str2] = value
3. Within a closure and scoped within that closure:
this[str1 + str2] = value
Within the closure, global and window will still set the global. Note that if you are within a function that is being called, 'this' could refer to another object.

It's not clear exactly what you're trying to accomplish, but you can access variables by name as properties of an object.
// this is the container to hold your named variables
// (which will be properties of this object)
var container = {};
function setVariableIndirectly(obj){
var second = obj.className; // returns "read"
var first = obj.parentNode.className; // returns "group"
// this is how you access a property of an object
// using a string as the property name
container[first + "_" + second] = "set this as the new variable";
// in your example container["read_group"] would now be set
}
It's probably better to put your variables on your own container object as shown above, but you can also access global variables via properties on the window object.

You can set a global variable this way:
window[first + "_" + second] = "set this as the new variable";
and access it as:
console.log(group_read);

Related

JavaScript - Get variable original name by it's prototype [duplicate]

This question already has answers here:
Variable name as a string in Javascript
(20 answers)
Closed 8 months ago.
How can i get the original name of the variable by it's prototype? I tried MyVar.name but it's not defined.
I have a function for example which get the original variable name.
function varName(v) {
return v.toString();
}
But when I call it with variable object, it returns [Object object].
varName(window);
I want to make it return the original variable name.
varName(window);
// window
;TLDR
The short but negative answer is it can't be done. Prototyping potentially applies to values stored in a variable, not to names used in code to refer to the variable. If you still have an insurmountable problem please edit the question to provide more details about the actual coding or design issue that remains.
Variable names
A variable name is an identifier used to access the location where the value of the variable is stored. There is no inverse relationship: the value of a variable contains no information about where it is stored.
Because JavaScript supports run time evaluation using variable names in expressions, the compiler and run time engine maintain "bindings" of variable names with the location where they are stored in memory. Such bindings are stored in global and function environment records. The structure and contents of the environment records are, however, not accessible from within JavaScript. You can no more determine the name of variable a function argument might have been stored in prior to being passed to a function by value that you could determine where in a scope chain of environment records a variable being read in code was defined.
As #traktor said, it cannot be done, but there is an available workaround for you:
Create a function, so that you can name your variable:
foo = function(name) {
this.name = name;
}
And, while creating one, call it:
var pear = new foo("pear");

How do i access a specific variable from another js file, based on conditions from my current js file?

function tidsbestilling() {
var valgtDato = document.getElementById('datepicker').value
console.log(valgtDato)
var getDato = "D" + valgtDato.substring(0, 2) + valgtDato.substring(3, 5) + valgtDato.substring(6, 10)
console.log(getDato);
}
console.log(D31102019);
Im trying to access a const called D31102019 from another js file. The variable is date specific, so if the user chooses another date(ex. 30-10-2019), i want to be accessing the variable D30102019 instead. How can i make the "getDato" variable(currently defined as "D31102019"), into something i can actually use to access the const from the other file?
If it is a global variable it will be in the scope of window, you can access it using:
var variableName = 'D31102019';
window[variableName];
Or in your case
window[tidsbestilling()]
But you have to return the result from your function:
function tidsbestilling() {
var valgtDato = document.getElementById('datepicker').value;
var getDato = "D" + valgtDato.substring(0, 2) + valgtDato.substring(3, 5) + valgtDato.substring(6, 10);
return getDato;
}
This declaration creates a constant whose scope can be either global
or local to the block in which it is declared. Global constants do not
become properties of the window object, unlike var variables. An
initializer for a constant is required; that is, you must specify its
value in the same statement in which it's declared (which makes sense,
given that it can't be changed later)
If you choose using const which comes in the next version of javascript then you are supposed to export the constant from one file and then import that constant whereever you require using es6 module system. If you go with es5 then var is fine. But it is always a good idea to make your code modular avoiding globals.

Get variable name from within object instance [duplicate]

This question already has an answer here:
Find out instance variable name out of itself
(1 answer)
Closed 19 days ago.
I want to be able to access the var name of this class instance from inside a method.. Can I set the actual variable name as a string on the constructor or something?
var myClass = function(filePath){
this.run = function(){
// I want to access the string "x"
console.log( this.variableName ); // ????
};
};
var x = new myClass("./sayHi.js");
Pass the variable name as a parameter when you construct it
var myClass = function(assigned_name,filePath){
this.variableName = assigned_name
this.run = function(){
console.log( this.variableName );
}
}
var x = new myClass('x','./sayHi.js');
x.run()
Output:
'x'
Useful for:
While many people say this is pointless, I have run into a situation where I need it. And a side-note, many jQuery operations rely on the principle of knowing what its own variable name is. It is always '$'. And people refer to '$' from inside a jQuery method when assigning anonymous functions to onclick events without realizing that it is exactly what your question is asking for.
You will need this if your myClass() object dynamically assigns event handlers that call-back to your specific class instance, as these calls are often reliant on information saved in your specific class variable. Since your myClass() function isn't as wide-spread as jQuery, you can't count on it always being assigned to the same variable, like '$'.
Passing its own assigned variable name to itself when it is constructed is the best way I've found to let my class instance know what its global reference is.

javascript variable and value concatenation

I have a list of variables:
subcatlist1 = 'aa';
subcatlist2 = 'bb';
subcatlist3 = 'cc';
What i would like to do, is insert the value of a given variable from the option options, into an element, but the 'number' of the variable (ie, 1, 2 or 3) is itself coming in as a variable, say itemNumber.
What I would like to do is:
$(element).html(subcatlist+ itemNumber);
... Which would give the value of aa for itemNumber = 1
The error that I am getting is:
ReferenceError: subcatlist is not defined - which make sense, because the variable subcatlist doesn't exist - only subcatlist1, subcatlist2, subcatlist3 exist.
Do how can i concatenate the subcatlist+ itemNumber to get a variable that i can use, as subcatlist1 etc?
Thanks
Use object instead of variable is better approach in your context,Because you concadenate with variable is wrong.
var subcatlist = {1:"aa",2:"bb",3:"cc"}
$(element).html(subcatlist[itemNumber]);
Updated
The solution is to access the needed variable as a property of the containing object.
If defined in the global scope using var , in javascript the value is assigned as a property of the global object, and it can be accessed using the self explanatory keyword globalThis
In JavaScript, there's always a global object defined. In a web browser, when scripts create global variables defined with the var keyword, they're created as members of the global object. (In Node.js this is not the case.)
var subcatlist1 = 'aa';
var subcatlist2 = 'bb';
var subcatlist3 = 'cc';
var itemNumber = parseInt(Math.random() * 3) + 1
$('#test').html(globalThis['subcatlist' + itemNumber])
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">
See also "Variable" variables in JavaScript
Original answer
If having a list of variables is mandatory you could use eval() like this:
$(element).html(eval("subcatlist"+ itemNumber));
eval can be harmful and should be avoided in most cases

What does "var" do in JavaScript? Why is it sometimes part of an assignment? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Difference between using var and not using var in JavaScript
var foo = 1;
foo = 1;
What is the difference between above two lines ?
Basically, var declares a variable and you can also assign to it at the same time.
Without var, it's assigning to the variable. Assigning will either assign to an existing variable or create a global variable of that name then assign to it.
Outside of functions, that means there's no real difference (in principal) if the variable does not already exist. Both create the global variable foo in that case.
Within a function, there's a huge difference. The first creates a variable local to the function regardless of whether or not it exists elsewhere.
The second will create a global variable if it doesn't exist, or simply change the value if it does exist.
In order to keep code as modular as possible, you should always use var unless you are specifically wanting to change existing global variables. That means declaring all globals outside of functions with var and declaring all locals with var.
foo = 1 will put foo in the last scope where foo was defined, or the global scope. var foo = 1 will put the variable in the current scope (i.e. the current function).
In first case foo will be available in the same scope where it is defined, i.e. it will be local variable.
In second case foo is a global variable, located in global scope.

Categories