我有一种感觉,这可能是不可能的,但我想确定在javascript中传递给函数的变量的原始变量名。我不知道如何更好地解释它,所以看看这个例子是否有意义。
function getVariableName(unknownVariable){
return unknownVariable.originalName;
}
getVariableName(foo); //returns string "foo";
getVariableName(bar); //returns string "bar";
这是我正在开发的一个jquery插件,我希望能够显示传递给"debug“函数的变量的名称。
发布于 2010-08-04 17:08:17
你说得对,这在任何情况下都是不可能的,因为只有值被传递到函数中。
发布于 2017-09-15 09:28:34
多亏了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"
唯一(小)的问题是你必须在{}
之间包装你的未知变量,这没什么大不了的。
发布于 2014-06-08 03:37:07
所有的全局变量都是全局对象(this或window)的属性,不是吗?因此,当我想要找出变量的名称时,我创建了以下函数:
var getName = function(variable) {
for (var prop in window) {
if (variable === window[prop]) {
return prop;
}
}
}
var helloWorld = "Hello World!";
console.log(getName(helloWorld)); // "helloWorld"
有时不起作用,例如,如果创建的两个字符串没有使用new运算符,并且具有相同的值。
https://stackoverflow.com/questions/3404057
复制相似问题