Concatenate name variable (not value) Js - javascript

My problem is simple:
I want to concatenate a dynamic variable name in a function, so with the name insert in parameter, when I call the function, she concat automatically the string in the new variable name.
Exemple (wrong, I think):
function blockDL(insertName){
return var 'block' + insertName + 'DT'= document.createElement('dt');
};
blockDL('First');
I expect the code return:
blockFirstDT = document.createElement('dt');
Thanks for your help ! =)

What you want is not possible. See "Variable" variables in Javascript? for alternatives of what you can do.
However, "variable variables" is usually a indicator of bad code design. Especially in your case, there is absolutely no reason or benefit to do any of these. Just name the variables blockDT and paraphDT or whatever you want.

The only way you will be able to use a string for a variable name is by placing it as the property of another object. if you want the variable global you could use the window object.
window['block' + insertName + 'DT'] = document.createElement('dt');
that said, you really shouldn't need to and should probably look for other ways of structuring your code.

Related

Firebase, variable as key name

what I basically want to do is this:
variable = 'whatever';
fb.set({ variable : "More Stuff" });
So this will result in an entry that looks like:
whatever: "More Stuff"
Currently it just ends up as
variable: "More Stuff"
Can this be done?
For the latest version of Firebase, use brackets around the variable name:
firebase.database().ref("pathName").set({[variable] : 'MoreStuff'});
Using the other method of setting the index of the variable to the value will create an additional layer in the database structure.
Yes. The code is not working as expected because you are using object literal notation, which is the reason the it keeps the variable name as key, because that is how the notation works.
Solution
foo = {};
foo[variable] = 'more stuff';
fb.set(foo);
Turns out that #randomnamehere 's command didn't quite deliver what I expected, since I wanted to use a accumulated number - or in your case, a named index - inside a reference while still keeping multiple indexes. So the proper command should have actually been
firebase.database().ref(`pathName/${variable}`).set('More Stuff');
His original answer would actually replace the entire reference with a single named index inside it. I know because I learned it the hard way :P
You can create an Empty object and set your variable as it's property and assign a value to it. Please see below:
let object: any = {};
object[variable] = value

How does one check if a javascript variable is referenced, and from where?

JS does not have public/private variables, but everything is accessible from pretty much anywhere.
Is it possible to check what other variables reference another variable?
var firstVar = "Hello";
someObject.secondVar = firstVar;
checkReferences(someObject.secondVar);
=> firstVar
Or something along these lines.
someObject.secondVar would have the same value as firstVar, but it doesn't reference it. If you change the value of one, it won't change the value of the other.
Sorry for asking a question I was close to finding out the answer to.
I should have asked whether or not JS passes by reference or value. It's by value, until you pass Objects {}. So the question does not really make sense.
This answer is good reading for anyone who was wondering the same as me

Accessing Object's Data Via Another Variable Name

It's super late and my mind is blanking right now, but let's say I have variable filename and it's storing the name of another variable marker. The variable marker is an array and contains the object & property position: new google.maps.LatLng(42.2550,-114.3221).
I've been stupidly trying to access it via filename.position which of course returns undefined, since it's searching the literal filename for a 'position' property that does not exist.
But how could I pull marker.position by using filename? Is there some nifty jQuery trick for, uh, 'resolving' a variable to its contents? I'm brain fried. I know I've done this before.
If it's possible in your script, you can store the data not just in variable, but in a property of some object (usually it's more convenient to use global one).
For example
var myObj = {};
myObj.marker = new google.maps.LatLng(42.2550,-114.3221); // or anything else
Then you will be able to get this property using a variable like this:
myObj[filename].position
In this case i would also recomment to check for myObj[filename] existance using typeof structure, just to make sure such property exists in myObj.
if (typeof myObj[filename] !== "undefined") {
// do something
}
As apsillers noted, you could use global window object for this as well. But if your marker variable was defined inside some other function (i.e. not global), you won't be able to access it with window.marker or window[filename] as it will be out of scope.
Second way is to use eval() function which i'd strongly recommend to avoid.
Try this :
window[filename].position;

MooTools Chaining

I don't think a function/method should ever return void—instead, it should return this. That's why I was surprised to find out that this doesn't work:
$('buttonContainer').getElement('input').set('value', this.get('value') + ' ');
What the code is suppose to do is find an <input> that is a child of the element with id attribute value of buttonContainer, and add two space characters to its value attribute. The aforeshown code errors though, and I'm forced to write:
var input = $('buttonContainer').getElement('input');
input.set('value', input.get('value') + ' ');
Doesn't MooTools have a way to chain these two seperate statements into one? Something similar to my first snippet?
MooTools cannot rebind this on the fly for every method called. This would be impossible.
You have to understand that every single call to your chain is in the same scope, therefore this remains the same. jQuery and every single other framework have the same problem. If you want to do two operations on an element at the same time, you must store the object in a variable and then use that variable to reference the object exactly like you did in your second example:
var input = $('buttonContainer').getElement('input');
input.set('value', input.get('value') + ' ');
this can only change when the scope changes (which in JavaScript is always when you hit a brace {} enclosing a function). This is not a limitation of MooTools' chaining. It's the way JavaScript in general works.
What you are asking has nothing to do with chaining. this has no context, so your call fails. The solution you are not happy with is the way you will need to write it for other values/attributes, but for a straight forward change like this, write it this way:
$('buttonContainer').getElement('input').value += ' ';

When to use $ and when not to

I have selected a control using the following variable
var txt = $("#text1");
Now when I have to handle events on the textbox, do I have to reference it as $(txt) or txt will do
$(txt).keydown(function() {})
or
txt.keydown(function(){})
What is the advantage. Please explain it taking the variable txt as the context.
If txt is already equal to a jquery object, there is no need to use $(txt) as it's just extra processing to return the same thing.
The best approach is to declare your variables so know what they are. Basically, what I'm saying is apply some apps hungarian and prefix your jQuery variables with a $
var $text1 = $("#text1"); // this is a jQuery object
var text1 = $text1[0]; // this is not
A bit more info on Chad's response.
The $() is a short cut to the commonly used function
document.getElementById().
Once you lookup and store the object's value you don't need to look it up again. As Chad mentioned. Ask your self is the variable an object or a name (string), if it's a name you will have to lookup the object.
In my experience I've found that using $(txt) yields more predictable results compared to assigning it as a reference ans using the reference to call the same methods/properties. It's possibly superstition on my part, however a few of us at work have been foiled by using a reference such as txt rather than an implicit $(txt) once txt has been assigned.

Categories

Resources