【问题标题】:Get the name property of a variable [duplicate]获取变量的名称属性[重复]
【发布时间】:2013-09-11 12:29:48
【问题描述】:

我想知道是否可以在 javascript 或 JQuery 中获取变量的名称。

假设我在 javascript 中声明了一个变量,例如:

var customerNr = "456910";

如果函数接收到变量,我如何返回变量的名称?

例如:

function getNameOfVariable(someVariable){
     //return name of someVariable;
}

如果我这样调用这个函数:

getNameOfVariable(customerNr);

函数必须返回一个值为“customerNr”的字符串。

如何在 jquery 或 javascript 中执行此操作?某种反思?

【问题讨论】:

  • 你不能,或者说你不应该!您可以使用 eval 或其他技巧来完成此操作,但归根结底,如果您需要变量的名称,您可能做错了什么。

标签: javascript jquery


【解决方案1】:

这根本不可能!

传递的参数甚至不必有名称。它可以是函数的返回值或原始文字(如"string"3)。

【讨论】:

    【解决方案2】:

    不,这是不可能的。只为原始数据类型传输值,而不是引用,那么您怎么知道变量的“名称”是什么?例如:

    var customerNr="456910";
    var customerNrAfterProcessing=customerNr;
    getNameOfVariable(customerNrAfterProcessing);
    

    它会返回customerNrAfterProcessing 还是customerNr

    但是,您可以用对象来模仿这种行为。

    var variableName = someMethodThatDeterminesVariableNameOrJustAConstantIfYouPrefer();
    var myVariables={};
    var myVariables[variableName]={};
    myVariables[variableName].value="456910";
    myVariables[variableName].variableName=variableName;
    
    function getNameOfVariable(someVariable){
        return someVariable.variableName;
    }
    getNameOfVariable(myVariables[variableName]);
    

    显然,这比直接使用 variableName 变量要多得多,但在一些更复杂的情况下可能是必要的。

    working with objects in JS reference

    【讨论】:

    • 如果有人以您的方式模仿行为,您只需将名称与参数一起传递:func(myVariable, 'myVariable')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 2010-10-29
    • 2011-11-02
    • 1970-01-01
    • 2011-02-15
    • 2012-04-05
    • 2013-07-16
    相关资源
    最近更新 更多