How to turn variable name into string in JS?

孤者浪人 提交于 2019-12-12 00:28:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!