Javascript:从变量本身引用变量名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5395370/
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-25 17:03:28  来源:igfitidea点击:

Javascript: Reference a variable name from the variable itself

javascript

提问by hookedonwinter

I want to create a quick function that will console.loga variable name and the value. I'd like the result of the function to show in the console: foo: bar.

我想创建一个console.log包含变量名称和值的快速函数。我想对函数的结果在控制台中显示:foo: bar

My basic idea for the function looks like this:

我对这个函数的基本想法是这样的:

function varlog(var_name)
{
    console.log(var_name + ": " + eval(var_name));
}

And I'd call is thusly:

我会这样称呼:

function someRandomFunction()
{
    var foo = "bar";
    // ... some stuff happens
    varlog("foo");
}

This works if foois global, but doesn't work in the example provided. Another option that also only works globally is using window[var_name]instead of the scary eval.

如果foo是全局的,则此方法有效,但在提供的示例中无效。另一个仅适用于全局的选项是使用window[var_name]而不是可怕的eval.

I don't think what I'm asking is possible, but I figured I'd throw it out there.

我不认为我要问的是可能的,但我想我会把它扔在那里。

I'm spending a lot of time attempting to be lazy. My current method is just console.log('foo: ' + bar);which works just fine. But now I just want to know if this is possible.

我花了很多时间试图变得懒惰。我目前的方法就是console.log('foo: ' + bar);效果很好。但现在我只想知道这是否可能。

Some other questions I referenced in searching for this / creating what I have now:

我在搜索此内容/创建我现在拥有的内容时引用的其他一些问题:

--

——

Edit: I'd love to just call varlog(foo), if the name "foo" can be derived from the variable.

编辑:varlog(foo)如果名称“foo”可以从变量派生出来,我很乐意只调用。

采纳答案by idbentley

The reason it doesn't work is because the variable foois not accessable to the function varlog! foois declared in someRandomFunction, and is never passed into varlog, so varloghas no idea what the variable foo is! You can solve this problem by passing the variable foointo the function(or using some sort of closure to make fooin the scope of varlog) along with its string representation, but otherwise, I think you are out of luck.

它不起作用的原因是因为foo函数无法访问该变量varlogfoo在 someRandomFunction 中声明,并且永远不会传入varlog,所以varlog不知道变量 foo 是什么!您可以通过将变量及其字符串表示形式传递给foo函数(或使用某种闭包foo在 的范围内生成varlog)来解决此问题,否则,我认为您不走运。

Hope this helps.

希望这可以帮助。

回答by sqln00b

Solution - (for your actual use case)- console.log({foo})

解决方案 - (针对您的实际用例)-console.log({foo})

In ES6IdentifierReferences are being accepted as PropertyDefinitions on the ObjectLiteral's PropertyDefinitionList(see compatibility chart):

ES6 中,IdentifierReferences 被接受为PropertyDefinitions 上的ObjectLiterals PropertyDefinitionList请参阅兼容性图表):

The variable nameis being set to the Object's Property's key
and the variable valueis being set to the Object's Property's value.

变量被设置为所述ObjectProperty的 和可变被设置为所述的的。key
ObjectPropertyvalue

As console.logshows Objects with their Propertiy/ies' keys and values you can use that to see both your variable's nameand valueby invoking console.log({foo}).

作为console.log显示Objects的他们Propertiy/ IES' keyS和value是你可以用它来查看您的变量的两个名称通过调用console.log({foo})

Note that when you initialize a single anonymous objectwith several variables as I did in the second console.logwhile they appear in the same order as initialized here in the snippet's output they might get reordered (alphabetically) elsewhere.

请注意,当您object像我在第二个中所做的那样使用多个变量初始化单个匿名变量console.log时,它们的出现顺序与此处在代码段输出中初始化的顺序相同,它们可能会在其他地方(按字母顺序)重新排序。

var testint = 3
var teststring = "hi"
var testarr = ["one", 2, (function three(){})]
var testobj = {4:"four", 5:"five", nested:{6:"six",7:"seven"}}
console.log({testint})
console.log({testint, teststring, testarr, testobj})

Answer - (to the question title)- Object.keys({foo})[0]

答案 - (针对问题标题)-Object.keys({foo})[0]

You can also use this shorthand Object Initializertogether with Object.keys()to straightly access the variable name:

您还可以使用此速记Object InitializerObject.keys()直接访问变量名称:

var name = "value"
console.log(Object.keys({name})[0])

回答by mhitza

While I'm not aware of such a possibility, I'd wanted to share a small idea:

虽然我不知道这种可能性,但我想分享一个小想法:

Object.prototype.log = function(with_message) {
  console.log(with_message + ":" + this);
}

var x = "string";
x.log("x");

Like I said, a small idea.

就像我说的,一个小想法。

回答by Chris Shouts

I don't believe what you want to do is possible.

我不相信你想做的事情是可能的。

The best alternative I can think of is to pass an object to varlogthat is basically a key-value hash:

我能想到的最好的选择是传递一个对象varlog,它基本上是一个键值哈希:

function varlog(obj)
{
    for (var varname in obj) {
        console.log(varname + ": " + obj[varname]);
    }
}


function someRandomFunction()
{
    var foo = "bar";
    // ... some stuff happens
    varlog({foo: foo});
}

回答by clark

Kind of combining a couple of anwers into a small function

有点像将几个答案组合成一个小函数

Would this work for you?

这对你有用吗?

const log = function() {
  const key = Object.keys(this)[0];
  const value = this[key];
  console.log(`${key}: ${value}`);
}

let someValue = 2;

log.call({someVlaue}); //someValue: 2

Works with function too, even itself.

也适用于函数,甚至它本身。

log.call({log});

// It would return the following
log:function() {
  const key = Object.keys(this)[0];
  const value = this[key];
  console.log(`${key}: ${value}`);
}

回答by Robert Li

I don't think that there is a direct way to do what you asked for. However, I would suggest making that variable and array, where the first string or number in the array will be the wanted input and the second string will be the variable name.

我不认为有一种直接的方法可以做你所要求的。但是,我建议制作该变量和数组,其中数组中的第一个字符串或数字将是所需的输入,第二个字符串将是变量名称。

var name = "John"; //Original. No way to get the name

var name = ["John", "name"]; /*My way. Variable input will be at name[0] and name
name[1] */

If your variable is already an array, simply add the name to the last position in the array.

如果您的变量已经是一个数组,只需将名称添加到数组中的最后一个位置。

回答by rafaelcastrocouto

I loved @mhitza idea, so I'm making it a little bigger...

我喜欢@mhitza 的想法,所以我要把它做得更大一些......

The downside is the need to use .valueto reach the variable content.

缺点是需要使用.value达到可变内容。

Object.prototype.log = function(message) {
  if (message) console.log(this.name, this.value, message);
  else console.log(this.name, this.value);
}

function nar (name, value) {
  var o = {name: name, value: value};
  this[name] = o;
  return o;
}

// var globalVar = 1;
nar('globalVar', 1); 

globalVar.log();
// > globalVar 1

globalVar.value += 5;

globalVar.log('equal six');
// > globalVar 6 equal six

var someFunction = function () {
  // var localVar = 2;
  nar('localVar', 2);

  localVar.log('someInfo');
  // > localVar 2 someInfo
};

someFunction();