Javascript:从变量本身引用变量名 [英] Javascript: Reference a variable name from the variable itself

查看:94
本文介绍了Javascript:从变量本身引用变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我的基本想法对于函数看起来像这样:

My basic idea for the function looks like this:

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

我打电话的是:

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

如果 foo 是全局的,但在提供的示例中不起作用。另一个也只能全局工作的选项是使用窗口[var_name] 而不是可怕的 eval

This works if foo is 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.

我不认为我问的是可能的,但我想我会把它扔出去。

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

我花了很多时间试图变懒。我当前的方法只是 console.log('foo:'+ bar); 哪个工作正常。但现在我只想知道这是否可行。

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.

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

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

  • Variable name as a string in Javascript
  • How to convert variable name to string in JavaScript?
  • Javascript, refer to a variable using a string containing its name?
  • How to find JavaScript variable by its name

-

编辑:我只想打电话给 varlog (foo),如果可以派生名称foo来自变量。

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

推荐答案

它不起作用的原因是因为变量 foo 无法访问函数 varlog foo 在someRandomFunction中声明,并且永远不会传递到 varlog ,所以 varlog 不知道变量foo是什么!你可以通过将变量 foo 传递给函数来解决这个问题(或者使用某种闭包来使 foo 进入 varlog 的范围及其字符串表示,但除此之外,我认为你运气不好。

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

希望这会有所帮助。

这篇关于Javascript:从变量本身引用变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆