Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/408.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Javascript中是否可以获取变量的名称?_Javascript - Fatal编程技术网

在Javascript中是否可以获取变量的名称?

在Javascript中是否可以获取变量的名称?,javascript,Javascript,我知道这完全没用,但我还是很好奇。有可能做下面这样的事情吗 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

我知道这完全没用,但我还是很好奇。有可能做下面这样的事情吗

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

这将返回传递给函数的所有参数的名称数组。

nope,但您可以使用
arguments
string为什么需要该名称?不,您不能这样做。在调用环境中提到
x
会导致传递
x
的值,并且一个值就是一个值;它与变量没有内在关系。为什么需要打印变量名?我不禁想知道,为什么要这样做?这将返回形式参数名-函数定义中的名称。OP想要函数调用中引用的变量名——实际参数。啊,对了。它满足“V”示例,但不满足X和Y条件:-/
function getArgNames(fn) {
    var matches = fn.toString().match(/\(([a-z_, ]+)\)/i);
    if (matches.length > 1) {
        return matches[1].replace(/\s+/g, '').split(',');
    }
    return [];
}