Get variable names with JavaScript - javascript

I want to create a log function where I can insert variable names like this:
var a = '123',
b = 'abc';
log([a, b]);
And the result should look like this in the console.log
a: 123
b: abc
Get the value of the variable is no problems but how do I get the variable names? The function should be generic so I can't always assume that the scope is window.

so the argument is an array of variables? then no, there is no way to get the original variable name once it is passed that way. in the receiving end, they just look like:
["123","abc"];
and nothing more
you could provide the function the names of the variables and the scope they are in, like:
function log(arr,scope){
for(var i=0;i<arr.length;i++){
console.log(arr[i]+':'scope[arr[i]]);
}
}
however, this runs into the problem if you can give the scope also. there are a lot of issues of what this is in certain areas of code:
for nonstrict functions, this is window
for strict functions, this is undefined
for constructor functions, this is the constructed object
within an object literal, this is the immediate enclosing object
so you can't rely on passing this as a scope. unless you can provide the scope, this is another dead end.
if you pass them as an object, then you can iterate through the object and its "keys" and not the original variable names. however, this is more damage than cure in this case.

I know you want to save some keystrokes. Me too. However, I usually log the variable name and values much like others here have already suggested.
console.log({a:a, b:b});
If you really prefer the format that you already illustrated, then you can do it like this:
function log(o) {
var key;
for (key in o) {
console.log(key + ":", o[key]);
}
}
var a = '1243';
var b = 'qwre';
log({
a:a,
b:b
});
Either way, you'd need to include the variable name in your logging request if you want to see it. Like Gareth said, seeing the variable names from inside the called function is not an option.

Something like this would do what you're looking for:
function log(logDict) {
for (var item in logDict) {
console.log(item + ": " + logDict[item]);
}
}
function logSomeStuff() {
var dict = {};
dict.a = "123";
dict.b = "abc";
log(dict);
}
logSomeStuff();

Don't know if this would really work in JS... but you can use a Object, in which you can store the name and the value:
function MyLogObject(name, value) {
this.name = name;
this.value = value;
}
var log = [];
log.push(new MyLogObject('a', '123'));
log.push(new MyLogObject('b', 'abc'));
for each (var item in log) {
if (item.value != undefined)
alert(item.name + "/" + item.value);
}
Then you can loop thru this Object and you can get the name and the value

You can't access the variable names using an Array. What you could do is use objects or pass the variable names as a String:
var x = 7;
var y = 8;
function logVars(arr){
for(var i = 0; i < arr.length; i++){
alert(arr[i] + " = " + window[arr[i]]);
}
}
logVars(["x","y"]);

I had a somewhat similar problem, but for different reasons.
The best solution I could find was:
MyArray = ["zero","one","two","three","four","five"];
MyArray.name="MyArray";
So if:
x=MyArray.name;
Then:
X=="MyArray"
Like I said, it suited my needs, but not sure HOW this will work for you.
I feel silly that I even needed it, but I did.

test this.
var variableA="valor01"; <br>
var variableB="valor02";
var NamevariableA=eval('("variableA")');<br>
var NamevariableB=eval('("variableB")');<br>
console.log(NamevariableA,NamevariableB);
atte.
Manuel Retamozo Arrué

Related

concatenate string with integer to use as a variable (creating dynamic variables) in jquery

I have an array ARRAY whose length is dynamic. In the below example it is 5 but it may be 10 or 15 also
ARRAY = [A,B,C,D,E];
var mlength = ARRAY.length;
Using this mlength, how can I create variables. For example
I want to assign as
mname0=ARRAY[0]; mname1 = ARRAY[1]; mname2= ARRAY[2]; mname3 = ARRAY[3]; mname4 = ARRAY[4];
I have tried the below code. But that's creating reference error Invalid left-hand side in assignment
for (var i = 0, mlength = ARRAY.length; i < mlength; i++) {
'mname'+i = ARRAY[i];
}
How can I create dynamic variables?
variables in the global scope could also be considered as members of the window-object:
var mname,ARRAY = ["A","B","C","D","E"];
var mlength = ARRAY.length;
for(var i=0;i<mlength;i++){
window["mname"+i]=ARRAY[i];
}
alert(mname0);
But you should consider working directly with ARRAY instead
Change to this:
var ARRAY = ['A', 'B', 'C', 'D', 'E'];
var mlength = ARRAY.length;
for (var i = 0; i < mlength; i++) {
console.log('mname' + i + ' = ' + ARRAY[i]);
}
This answer is taken from this question which I am the author. Yet I don't feel the question is a duplicate itself.
To create dynamic variable name, here 3 options.
eval (not recommended)
You can use the Javascript function eval to achieve what you want. But be aware, this in not recommended (I emphasized it twice, hope you understood!).
Don't use eval needlessly!
eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, third party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.
It would be used like that :
eval('var mname' + i + ' = "something";');
Window object notation (Better than eval, still not really recommended)
This method consist of using the object notation provided by JavaScript on the global window object. This is polluting the global window scope and can be overrided by other JS files which is bad. If you want to know more on that subject, this is a good question : Storing a variable in the JavaScript 'window' object is a proper way to use that object?.
To use that method, you would do thing like that :
window['mname' + i] = something;
alert(window[varName]);
Using an object (recommended)
The best solution would be to creating you own variable scope. For instance, you could create on the global scope a variable and assign an object to it. You can then use the object notation to create you dynamics variables. It work the same way as the window does :
var globalScope = {};
function awesome(){
var localScope = {};
globalScope['mname' + i] = 'something';
localScope['mname' + i] = 'else';
notSoAwesome();
}
function notSoAwesome(){
alert(globalScope['mname' + i]); // 'something';
alert(localScope['mname' + i]); // undefined
}
Try this,
var arr= [];
for(var i =0; i <15; i++) {
arr.push[{'mname'+i: 'ARRAY'+i}];
}
Here is the link where i have generated array
$(document).ready(function (e){
var cars = ["Saab", "Volvo", "BMW"];
var text='';
var mname="name";
for (i = 0; i < cars.length; i++) {
text += mname+i+'='+cars[i]+',';
}
alert(text);
});
where your increment value based on your requirement it will generated string dynamically.
I hope this will help you.
You can do something like this.
var mname;
var ARRAY = ['A','B','C','D','E'];
var mlength = ARRAY.length;
for(var i=0;i<mlength;i++){
window['mname'+i]=ARRAY[i];
}
console.log(mname1);
So this might help you. In this code I am making all the variables as window object member since Window is Global Object.

Make use of a global array

I want to use the values that I get from a request, but the response object is a local variable (an array). Therefore I create this global array:
<script type="text/javascript">
var response = [];
as you see, right under the script opening tag, so it is global. Then in the function where I have the response I added this:
jsonResponse.forEach(function(element){
response[element.size] = element.id;
});
And then added this, with the purpose to make use of the values that I've got in my global var from the response object:
getIdOfProductBySize: function() {
var selectedIndex = document.getElementById('dropdown_options').value;
for (var key in response) {
if (key != selectedIndex) {
continue;
} else {
return response[key];
}
}
}
Doesn't work, so I started going step by step (of the order I add the new things) and I noticed that the script breaks after the 2nd thing that I add (where the forEach is).
Maybe I am not declaring the global variable correctly, or maybe I cannot access it this way, or maybe I don't assign the values to it in the correct way, I don't know, so I am asking if someone can give me a hint how to make use of all this working together?
Try this:
var response = {key1: value1};
var i = 2;
jsonResponse.forEach(function(entry) {
console.log(entry);
response["key"+i] = entry.id;
i++;
});
var index;
for (index = 0; index < response.length; ++index)
{
console.log(response[index]);
if(response["key"+index] !== selectedIndex)
continue;
else
return response["key"+index];
}
Looks like you're going to need a two dimensional array.
Looks to me like your "key" value is undefined.
before:
for (var key in response) {
try:
var k=response.whatever;
If that makes sense?
response[element.id] = element.size;
Try this one, i believe element.size returns the actual size of an element and is not what you want to use as index in an array.

How to access a javascript object's property, when it has a dynamic number as property title?

I have an object which contains a variable number of arrays. The property title always is a number (like here: 15, 117). I could simply access the arrays with names[15] or names[117], but those values are changing constantly because of a data-request.
How can I access them as "the first" or "the second"???
var names = {
15: Array[1];
117: Array[1];
};
If this isn't working, I tried a for...in loop to store the arrays in variables, but it didn't really work out:
var name1, name2;
for(var key in names){
if(name1){name2 = names[key];}
if(!name1){name1 = names[key];}
}
As soon as there are more arrays, it's overriding name1 with name2 and so on...
Any idea how to solve this? Thanks already for your time.
I deleted my earlier answer, as i think is not accurate. js fiddle
var names ={1: ["a","b"],2:["c","d"],3:["e","f"]}
var nameArr=[],i=0; for(var key in names){ nameArr[i++] = names[key]; }
for(i=0;i<nameArr.length;i++)
alert(nameArr[i]);
There is example, how you can access to properties of your object with loop: http://jsfiddle.net/Y7mHB/
var names = {
15: '15',
117: '117'
};
for(var key in names) {
alert(key + ' ' + names[key]);
}
Yes that's absolutely true to access them like this. My problem is, I have to store them separately as variables, to then pass them to a function who could look like this:
var a = name[key];//the first object-property (how to store??)
var b = name[key];//the second object-property (how to store??)
function doSomething(a,b){
//do something usefull
}

Is there a way to make a dynamic variable name based on the value of another variable?

Is there a way to make the value of a variable the name for another variable? For example, I want the variable name (value_of_i) to be what ever number "i" is during that iteration. The while loop below is not what I'm using it for, it's just to explain what I'm asking.
var i = 1;
while(i<10)
{
var value_of_i = "This loop has ran " + i + "times.";
i++;
}
For the first iteration, "i" is equal to 1 so I would want the variable name to be "1":
var 1 = "This loop has ran " + i + "times.";
And the second interation:
var 2 = "This loop has ran " + i + "times.";
Yes. Using bracket notation (Here is a tutorial in MDN)
Here is a working fiddle
When doing something like containingObject[stringVariable] you are accessing the property in containingObject whose name is the value stored in stringVariable.
// this assumes browser JavaScript where window is the global namespace
// in node.js this would be a little different
var i=0;
while(i<10){
window["counters"+i] = "This is loop has ran " + i + "times.";
i++;
}
console.log(counters3);
If you'd like you can use this instead of window, however this might fail in strict mode.
Here is the main explanation of how bracket notation works from the MDN link above:
Properties of JavaScript objects can also be accessed or set using a bracket notation. Objects are sometimes called associative arrays, since each property is associated with a string value that can be used to access it. So, for example, you could access the properties of the myCar object as follows:
myCar["make"] = "Ford";
myCar["model"] = "Mustang";
myCar["year"] = 1969;
You can also access properties by using a string value that is stored in a variable:
var propertyName = "make";
myCar[propertyName] = "Ford";
propertyName = "model";
myCar[propertyName] = "Mustang";
You can't make a variable name a number, its not a valid name. So var 1="" is invalid.
But to dynamically set the value you can do
var x = "variablenamehere";
window[x] = "variablevaluehere";
Thats the same as
var variablenamehere
except that it will be scoped as a global variable and will be accessible everywhere, rather than being limited to the current function scope.
Why not store your strings in an array that is indexed by i?
That way you can reference them later efficiently and easily;
var loopI = new Array();
for(var i = 0; i < 10; ++i) {
loopI[i] = "This loop has ran " + i + "times.";
}
This works:
var o = {};
var d = "dog";
for (var k = 0; k < 5; k += 1) {
o[d+k] = k*100;
}
console.log(o.dog3); // 300
This comes closer to doing what you want:
var N = {};
var M = {};
var i = 1;
while(i<10)
{
N[i] = "This loop ran " + i + " times.";
// Or, so you can use dot notation later:
M['OO'+i] = "This loop ran " + i + " times.";
// Those are capital O's, not zeros. Numbers won't work.
i++;
}
console.log(N[3]); // This loop ran 3 times.
console.log(M.OO7); // This loop ran 7 times.
The 'OO' notation could cause bewilderment and wasted time for others trying to use your code; but it could also be a source of amusement for them. This reminds me of a chess board after white's first two moves are to bring out a knight and then put it back. The board then seems to show that black moved first, and some people will endlessly insist that the configuration proves there was illegal play unless someone tells them what happened.

Creating objects of unknown size NOT using eval

I'm currently using javascript eval() to check and create a multidimensional object that I have no idea of the depth.
Basically, I want to know if there's any way to create this multi-depth object. The object can be as deep as result['one']['two']['three']['four']['five']['six']['seven']. I know there are cases where using eval() is perfectly fine, but I'm also worried about performance. I thought about referencing each depth to a new variable, but I don't know how to do pointers in Javascript
create = function(fields, create_array){
var field;
for (j = 0; j < len; j++){
field = fields.slice(0, j).join('');
if (field){
// is there any way to do this without eval?
eval('if (typeof result' + field + ' == "undefined" || !result' + field + ') result' + field + ' = ' + (create_array?'[]':'{}') + ';');
}
}
}
How about
var deep = { one: { two: { three: { four: { five: { six: { seven: 'peek-a-boo!' }}}}}}};
I don't see what "eval()" has to do with this at all; there's no reason to "initialize" such an object. Just create them.
If you wanted to write a function with an API like you've got (for reasons I don't understand), you could do this:
function create(fields, create_array) {
var rv = create_array ? [] : {}, o = rv;
for (var i = 0; i < fields.length; ++i) {
o = o[fields[i]] = create_array ? [] : {};
}
return rv;
}
There doesn't seem to be any point to the "create_array" flag, since you're presumably always using strings for keys.
Never mind, found my way in. I used a recursive function to ensure that the object was created properly.
create = function(create_array, res, path){
var field = fields.shift();
if (field){
if (typeof res[field] == "undefined" || !res[field]) res[field] = (create_array?[]:{});
path.push('["' + field + '"]');
create(create_array, res[field], path);
}
}
var result = {}, strpath = [], fields[];
create(true, result, strpath);
eval('result' + strpath.join('') + ' = value;');
being variable "field" a variable outside the function, that contained the levels of the object. doing result["field"]["name"]["first"] = value without the ["field"] or ["name"] field existing or defined as an object, would throw an error and stop execution, that's why I'm pre-creating the object variable, either as an array or object.
I couldn't find another option for the second eval() though. There's no way to provide a way to access multiple properties on an object without knowing the depth.

Categories