Is there a way to retrieve a variable's name in JavaScript without it being part of an object? Here's an example of what I'm trying to achieve:
var obj = {//Declared in a global scope
init:function(){
var var1 = /*value from input*/;
var var2 = /*value from input*/;
doCode({name:/*variable name as a string, "var1"*/,val:var1});
doCode({name:/*variable name as a string, "var2"*/,val:var2});
function checkNumber(args){
if(typeof args.val != 'number')
console.error("Error variable '"+arg.name+"' is not a number!");
else
console.log("Variable '"+arg.name+"' is a number!");
}
}
}
obj.init();
asked Jun 28, 2013 at 13:46
PhilTrep
1,6512 gold badges12 silver badges23 bronze badges
1 Answer 1
This might work
var foo = 'bar'
var fooname
for (var i in window) {
if (window[i] == foo) fooname = i
}
alert(fooname) // alerts 'foo'
upd Of course, that have some restrictions, for example you can't have two variables with same content, but it is the only way I still found.
answered Jun 28, 2013 at 14:17
TulaGingerbread
4655 silver badges15 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
PhilTrep
I wont use this in a global scope but with an object instead, thank you! +1 and correct.
Explore related questions
See similar questions with these tags.
lang-js
checkNumberonce with one variable as its argument or the value is unique among some object you can access from the function, the answer is "no". Why do you want to do this?var1andvar2declared ?thisreally is, that's why I asked ?data-labelattribute or something, then checkarg.valueand usearg.dataset.label. (Note that yourtypeofcheck probably doesn’t perform as intended if this is user input...)