简体   繁体   English

我可以将函数的参数转换为其自己的变量名称吗?

[英]Can I convert the argument of a function into its own variable's name?

So I want to have something like this: 所以我想要这样的东西:

function trace(variable){
    console.log(variables_name.toString()+":"+variable);
}

Is this possible, and if so, how can I invoke/print the variable's name? 这可能吗?如果可以,如何调用/打印变量名?

This way I can succinctly write trace(a_variable) and have a good idea of what it is without having to write console.log("variable name: "+ variable); 这样,我可以简洁地编写trace(a_variable) ,而不必编写console.log("variable name: "+ variable);

You could pass a map: 您可以通过地图:

function trace(variableMap){
    for (var key in variableMap){
        console.log(key+":"+variableMap[key]);
    }
}

trace ({someVar : someVar});

Since a mod accepted this answer for OP I'll go ahead and add that simply doing 由于国防部接受了OP的答案,因此我将继续添加

trace({someVar});

Also seems to work. 似乎也可行。 This notation depends on ECMAScript 6 is called the Object Literal Property Value Shorthand . 此表示法取决于ECMAScript 6,称为“ 对象文字属性值速记”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将变量作为参数传递给另一个函数后,能否以字符串形式访问变量的名称? - Can I access a variable's name as a string after passing it as an argument to another function? 如何使用变量而不是名称来调用函数? - How can I call a function by using a variable instead of its name? 为什么我不能通过传递它的变量名来运行这个回调,但我可以将它包装在一个函数中? - Why can't I run this callback by just passing its variable name, but I can wrap it in a function? 如何将我的功能提取到自己的模块中? - How can I extract my function into its own modules? 我可以使用父函数的参数来命名其子函数吗? - Can I use a parent function's parameter to name its child function? 有没有办法在 function 中更改变量的值? - Is there a way to change a variable’s value given its name in a function? 从自己的函数中获取属性的名称 - Get name of property from its own function 为什么不能将变量名作为字符串获取? 我想创建自己的“ console.log”功能 - Why can't I get the variable name as a string? I want to create my own 'console.log' function 如何使WebStorm在其单独的行上格式化每个函数调用参数,并与左括号对齐? - How do I get WebStorm to format each function call argument on its own line, aligned to the opening parenthesis? javascript文件可以获得自己的名字吗? - Can javascript file get its own name?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM