代码之家  ›  专栏  ›  技术社区  ›  Andy Groff

确定传递给函数后变量的原始名称

  •  23
  • Andy Groff  · 技术社区  · 16 年前

    function getVariableName(unknownVariable){
      return unknownVariable.originalName;
    }
    
    getVariableName(foo); //returns string "foo";
    getVariableName(bar); //returns string "bar";
    

    这是针对我正在开发的jquery插件,我希望能够显示传递给“debug”函数的变量的名称。

    6 回复  |  直到 16 年前
        1
  •  22
  •   Andrei V    11 年前

    你说得对,这在任何理智的情况下都是不可能的,因为只有值被传递到函数中。

        2
  •  9
  •   Offirmo    9 年前

    由于ES6,这一点现在可以实现:

    function getVariableName(unknownVariableInAHash){
      return Object.keys(unknownVariableInAHash)[0]
    }
    
    const foo = 42
    const bar = 'baz'
    console.log(getVariableName({foo})) //returns string "foo"
    console.log(getVariableName({bar})) //returns string "bar"

    唯一(小)的问题是,必须将未知变量包装在 {} ,这没什么大不了的。

        3
  •  2
  •   RunninglVlan    11 年前

    因此,当我想找出变量的名称时,我做了以下函数:

    var getName = function(variable) {
      for (var prop in window) {
        if (variable === window[prop]) {
          return prop;
        }
      }
    }
    var helloWorld = "Hello World!";
    console.log(getName(helloWorld)); // "helloWorld"
    

    有时不起作用,例如,如果创建的两个字符串没有新运算符,并且具有相同的值。

        4
  •  1
  •   Helwor    7 年前

    当您需要调试时(显示var的名称和var的值), 我也一直在找,只想和大家分享我的发现。

    不需要eval,也可以使用非常简单的代码,在条件下将var传递到函数中,并在其周围加引号,然后全局声明变量:

    foo = 'bar';
    
    debug('foo'); 
    
    function debug(Variable) { 
     var Value = this[Variable]; // in that occurrence, it is equivalent to
     // this['foo'] which is the syntax to call the global variable foo
     console.log(Variable + " is " + Value);  // print "foo is bar"
    }
    
        5
  •  0
  •   Jude    10 年前

    将一组唯一变量转换为一个JSON对象,我为其编写了此函数

    function makeJSON(){ //Pass the variable names as string parameters [not by reference]
    ret={};
    for(i=0; i<arguments.length; i++){
        eval("ret."+arguments[i]+"="+arguments[i]);
    }
    return ret;
    }
    

    例子:

    a=b=c=3;
    console.log(makeJSON('a','b','c'));
    

    也许这就是这个问题的原因

        6
  •  0
  •   styfle    8 年前

    全局w/string方法

    下面是一种技巧,您可以使用它来保留变量的名称和值。

    // Set up a global variable called g
    var g = {};
    // All other variables should be defined as properties of this global object
    g.foo = 'hello';
    g.bar = 'world';
    
    // Setup function
    function doStuff(str) {
      if (str in g) {
        var name = str;
        var value = g[str];
        // Do stuff with the variable name and the variable value here
        // For this example, simply print to console
        console.log(name, value);
      } else {
        console.error('Oh snap! That variable does not exist!');
      }
    }
    
    // Call the function
    doStuff('foo'); // log: foo hello
    doStuff('bar'); // log: bar world
    doStuff('fakeVariable'); // error: Oh snap! That variable does not exist!

    这有效地创建了一个将变量名映射到其值的字典。如果不重构每个变量,这可能不适用于现有代码。但是使用这种方式,您可以实现这类问题的解决方案。

    initialize 一个具有名称和值的对象,它几乎可以实现您正在尝试的操作。

    function getVariableName(unknownVariable) {
      return Object.keys(unknownVariable)[0];
    }
    
    var foo = 'hello';
    var output = getVariableName({ foo }); // Note the curly brackets
    console.log(output);

    这是因为您使用键创建了一个新对象 foo hello

    功劳归于 this tweet

        7
  •  0
  •   Chris Perry    5 年前

    将2D引用数组与.filter()一起使用

    注意:我现在觉得上面@Offermo的答案是最好的。把我的答案留作参考,尽管我基本上不建议使用它。

    这是我独立提出的,它需要更多的输入,并且只适用于唯一的值(但如果这两个条件都满足的话,它就会起作用。)

    // Initialize some variables
    let var1 = "stick"
    let var2 = "goo"
    let var3 = "hello"
    let var4 = "asdf"
    
    
    // Create a 2D array of variable names
    const varNames = [
        [var1, "var1"],
        [var2, "var2"],
        [var3, "var3"]
    ]
    
    
    // Return either name of variable or `undefined` if no match
    const getName = v => varNames.filter(name => name[0] === v).length
      ? varNames.filter(name => name[0] === v)[0][1]
      : undefined
    
    
    // Use `getName` with OP's original function
    function getVariableName(unknownVariable){
      return getName(unknownVariable)
    }
    
    
        8
  •  -1
  •   voathnak    6 年前

    getVariableName({foo});