在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 [];
}