问题
I am trying to write a convenience wrapper for console.log, and I would like to print any variables passed in along with their contents.
Can I turn a variable name into a string in js?
回答1:
Assuming you want something like this:
function Log(data)
{
console.log(input variable name, data);
}
Then I don't think it is possible:
For convenience.. you could do something like
console.log({ "your variable name": your variable});
Which turns the input to an object that does contain the variable name you want to log. A little more typing, but perhaps makes the console output more readable.
回答2:
There is a possibility. And here is how
var passed_variable = '65'; // The actual variable
var varname = 'passed_variable'; // The name of the variable in another variable
Now, pass the varname
around but not the actual variable. When you need to the value of the variable you can simply do :
console.log(varname, ' : ', window[varname]); // Outputs, passed_variable : 65
I hope you find a way not to use this. :)
来源:https://stackoverflow.com/questions/19074583/how-to-turn-variable-name-into-string-in-js