使用 JavaScript 获取变量名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10276080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:17:22  来源:igfitidea点击:

Get variable names with JavaScript

javascript

提问by arpo

I want to create a log function where I can insert variable names like this:

我想创建一个日志函数,我可以在其中插入这样的变量名:

var a = '123',
    b = 'abc';

log([a, b]);

And the result should look like this in the console.log

结果在 console.log 中应该是这样的

a: 123
b: abc

Get the value of the variable is no problems but how do I get the variable names? The function should be generic so I can't always assume that the scope is window.

获取变量的值没有问题,但是如何获取变量名称?该函数应该是通用的,所以我不能总是假设范围是窗口。

采纳答案by Joseph

so the argument is an array of variables? then no, there is no way to get the original variable name once it is passed that way. in the receiving end, they just look like:

所以参数是一个变量数组?那么不,一旦以这种方式传递,就无法获得原始变量名称。在接收端,它们看起来像:

["123","abc"];

and nothing more

仅此而已



you could provide the function the names of the variables and the scope they are in, like:

您可以为函数提供变量的名称和它们所在的范围,例如:

function log(arr,scope){
    for(var i=0;i<arr.length;i++){
        console.log(arr[i]+':'scope[arr[i]]);
    }
}

however, this runs into the problem if you cangive the scope also. there are a lot of issues of what thisis in certain areas of code:

但是,如果您也可以提供范围,这就会遇到问题。this某些代码区域存在很多问题:

  • for nonstrict functions, thisis window
  • for strict functions, thisis undefined
  • for constructor functions, thisis the constructed object
  • within an object literal, thisis the immediate enclosing object
  • 对于非严格函数,thiswindow
  • 对于严格函数,thisundefined
  • 对于构造函数,this是构造对象
  • 在对象字面量中,this是直接封闭对象

so you can't rely on passing thisas a scope. unless you can provide the scope, this is another dead end.

所以你不能依赖this作为范围传递。除非你能提供范围,否则这是另一个死胡同。



if you pass them as an object, then you can iterate through the object and its "keys" and not the original variable names. however, this is more damage than cure in this case.

如果将它们作为对象传递,则可以遍历对象及其“键”而不是原始变量名称。然而,在这种情况下,这是伤害大于治疗。

回答by matty

I know you want to save some keystrokes. Me too. However, I usually log the variable name and values much like others here have already suggested.

我知道您想保存一些按键。我也是。但是,我通常会像这里其他人已经建议的那样记录变量名称和值。

console.log({a:a, b:b});

If you really prefer the format that you already illustrated, then you can do it like this:

如果你真的更喜欢你已经说明的格式,那么你可以这样做:

function log(o) {
    var key;
    for (key in o) {
        console.log(key + ":", o[key]);
    }
}

var a = '1243';
var b = 'qwre';
log({
    a:a,
    b:b
});

Either way, you'd need to include the variable name in your logging request if you want to see it. Like Gareth said, seeing the variable names from inside the called function is not an option.

无论哪种方式,如果您想查看它,您都需要在日志记录请求中包含变量名称。就像 Gareth 所说,从被调用函数内部查看变量名称不是一种选择。

回答by Ivan Karajas

Something like this would do what you're looking for:

像这样的事情会做你正在寻找的东西:

function log(logDict) {
    for (var item in logDict) {
        console.log(item + ": " + logDict[item]);
    }
}

function logSomeStuff() {
    var dict = {};
    dict.a = "123";
    dict.b = "abc";
    log(dict);
}

logSomeStuff();

回答by Ronk

I had a somewhat similar problem, but for different reasons.

我有一个有点类似的问题,但出于不同的原因。

The best solution I could find was:

我能找到的最佳解决方案是:

MyArray = ["zero","one","two","three","four","five"]; 
MyArray.name="MyArray";

So if:

因此,如果:

x=MyArray.name;

Then:

然后:

X=="MyArray"

Like I said, it suited my needs, but not sure HOW this will work for you. I feel silly that I even needed it, but I did.

就像我说的,它适合我的需求,但不确定这对你有什么用。我觉得我什至需要它很愚蠢,但我做到了。

回答by Tobi

Don't know if this would really work in JS... but you can use a Object, in which you can store the name and the value:

不知道这在 JS 中是否真的有效......但是你可以使用一个对象,你可以在其中存储名称和值:

  function MyLogObject(name, value) {
    this.name = name;
    this.value = value;
  }


  var log = [];
  log.push(new MyLogObject('a', '123'));
  log.push(new MyLogObject('b', 'abc'));

  for each (var item in log) {
    if (item.value != undefined)
      alert(item.name + "/" + item.value);       
  }

Then you can loop thru this Object and you can get the name and the value

然后你可以遍历这个对象,你可以得到名称和值

回答by muffel

You can't access the variable names using an Array. What you could do is use objects or pass the variable names as a String:

您不能使用数组访问变量名称。您可以做的是使用对象或将变量名称作为字符串传递:

var x = 7;
var y = 8;

function logVars(arr){
    for(var i = 0; i < arr.length; i++){
        alert(arr[i] + " = " + window[arr[i]]);
    }
}

logVars(["x","y"]);

回答by user3507808

test this.

测试这个。

var variableA="valor01"; <br>
var variableB="valor02";

var NamevariableA=eval('("variableA")');<br>
var NamevariableB=eval('("variableB")');<br>

console.log(NamevariableA,NamevariableB);

atte. Manuel Retamozo Arrué

证明。曼努埃尔·雷塔莫佐·阿鲁埃