简体   繁体   English

获取作为函数参数的变量名作为字符串

[英]getting variable name which is a argument of the function as a string

I know we can get a variable name as a string like this:我知道我们可以得到一个变量名作为这样的字符串:

 const varToString = varObj => Object.keys(varObj)[0] const someVar = 42 const displayName = varToString({ someVar }) console.log(displayName);

But I want to know if there is a solution in JavaScript to get the variable name set as a argument in a function?但是我想知道 JavaScript 中是否有解决方案可以将变量名设置为函数中的参数?

 function foo(variable) { const varToString = varObj => Object.keys(varObj)[0] const displayName = varToString({ variable }) console.log(displayName); } const someVariable = ['string', 'another string']; foo(someVariable);

As you see I get the internal variable name inside the function which is expected here... I want the original variable name instead so in this case we should get someVariable .正如你所看到的,我在函数内部得到了内部变量名,这是预期的......我想要原始变量名,所以在这种情况下我们应该得到someVariable

Is there any solution or I'm just wasting my time?有什么解决方案,还是我只是在浪费时间?

In the first snippet, varToString() is called with an object with a named property, and then you can retrieve the property name as you are doing already.在第一个片段中,使用具有命名属性的对象调用varToString() ,然后您可以像之前一样检索属性名称。

In the second snippet, foo() receives an array object without any information about where it came from;在第二个片段中, foo()接收一个数组对象,但没有任何关于它来自哪里的信息; that is just how parameter passing works in javascript.这就是参数传递在 javascript 中的工作方式。
If you change that call to foo({ someVariable }) then you can make it work again, because then you have created a new object that has a named property.如果您将该调用更改为foo({ someVariable })那么您可以使其再次工作,因为您已经创建了一个具有命名属性的新对象。

I know we can get a variable name as a string like this:我知道我们可以得到一个变量名作为这样的字符串:

That doesn't get a variable name.没有得到变量名。 It gets a property name, which is inferred from a variable name elsewhere in the code.它获取一个属性名称,该名称是从代码中其他地方的变量名称推断出来的。

But I want to know if there is a solution in JavaScript to get the variable name set as a argument in a function?但是我想知道 JavaScript 中是否有解决方案可以将变量名设置为函数中的参数?

No. What's passed to the function is the value that came from the variable.号什么是传递给函数的是,从变量传来的 There is nothing that connects that value back to the variable.没有任何东西可以将该值连接回变量。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM