【问题标题】:Is it possible in Javascript to get the name of a variable? [duplicate]是否可以在 Javascript 中获取变量的名称? [复制]
【发布时间】:2015-06-15 05:08:22
【问题描述】:

我知道这完全没用,但我还是很好奇。是否可以执行以下操作?

function getVariableName ( v )
{
    // .... do something ..... 
    // return the string "v" 
}
var x = 69;
var y = "somestring";
console.log(getVariableName(x)); // prints "x" to the console
console.log(getVariableName(y)); // prints "y" to the console

【问题讨论】:

  • 不,但您可以使用arguments 字符串
  • 为什么需要这个名字?
  • 不,你不能那样做。调用环境中提到x,导致xvalue被传递,一个值就是一个值;它与变量没有内在关系。
  • 为什么需要打印变量名?
  • 我不禁想知道,你为什么要这样做?

标签: javascript


【解决方案1】:
function getArgNames(fn) {
    var matches = fn.toString().match(/\(([a-z_, ]+)\)/i);
    if (matches.length > 1) {
        return matches[1].replace(/\s+/g, '').split(',');
    }
    return [];
}

这将返回一个包含传入函数的所有参数名称的数组。

【讨论】:

  • 这将返回 正式的 参数名称 - 来自函数定义的名称。 OP 想要函数调用中引用的变量名称 - actual 参数。
  • 啊,对。它满足“V”示例,但不满足 X 和 Y 条件。 :-/
猜你喜欢
  • 2019-08-24
  • 2017-03-06
  • 1970-01-01
  • 1970-01-01
  • 2016-06-22
  • 1970-01-01
  • 2020-07-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多