提问人:Andy Groff 提问时间:8/4/2010 更新时间:11/26/2022 访问量:11457
确定变量传递给函数后的原始名称
Determine original name of variable after its passed to a function
问:
我有一种感觉,这可能是不可能的,但我想确定已传递给 javascript 中函数的变量的原始变量名称。我不知道如何更好地解释它,所以看看这个例子是否有意义。
function getVariableName(unknownVariable){
return unknownVariable.originalName;
}
getVariableName(foo); //returns string "foo";
getVariableName(bar); //returns string "bar";
这是针对我正在使用的jquery插件,我希望能够显示传递给“调试”函数的变量的名称。
答:
你是对的,这在任何理智的方式下都是不可能的,因为只有值被传递到函数中。
评论
全局 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!
这有效地创建了一个将变量名称映射到其值的字典。如果不重构每个变量,这可能不适用于现有代码。但是使用这种风格,您可以实现此类问题的解决方案。
ES6 对象方法
在 ES6/ES2015 中,您可以初始化一个具有名称和值的对象,这几乎可以实现您想要做的事情。
function getVariableName(unknownVariable) {
return Object.keys(unknownVariable)[0];
}
var foo = 'hello';
var output = getVariableName({ foo }); // Note the curly brackets
console.log(output);
这之所以有效,是因为您创建了一个新对象,其键和值与变量 foo 相同,在本例中为 。然后,我们的帮助程序方法将第一个键作为字符串获取。foo
hello
评论
g
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"
有时不起作用,例如,如果在没有新运算符的情况下创建了 2 个字符串并且具有相同的值。
评论
window
window.a=1;window.b=1;
将一组唯一变量转换为一个 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'));
也许这就是这个查询的原因
评论
ret[x] = x
;这里绝对没有理由!eval
多亏了 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"
唯一(小)的问题是你必须将未知变量括在 之间,这没什么大不了的。{}
评论
{foo}
只是......所以你只是把它作为一个对象发送。请参阅:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/...{foo:42}
New notations in ECMAScript 2015
unknownVariableInAHash + 1
{}
如您所要调试(显示 var 的名称和 var 的值), 我也一直在寻找它,只想分享我的发现。
它不是通过从 var 中检索 var 的名称,而是相反:从 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"
}
我想你可以用
getVariableName({foo});
评论
使用带有 .filter() 的 2D 参考数组
注意:我现在觉得上面@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)
}
这是我对同时记录输入名称及其值的看法:
function logVariableAndName(unknownVariable) {
const variableName = Object.keys(unknownVariable)[0];
const value = unknownVariable[variableName];
console.log(variableName);
console.log(value);
}
然后你可以像logVariableAndName({ someVariable })
评论
nameof(foo) // returns the string "foo"