使用JavaScript获取变量名称 [英] Get variable names with JavaScript

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

问题描述

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

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

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

log([a, b]);

结果在console.log中应如下所示

And the result should look like this in the 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.

推荐答案

所以参数是一个变量数组?那么没有,一旦通过这种方式就没有办法得到原始的变量名。在接收端,它们看起来像:

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"];

并且不再是

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

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 can give the scope also. there are a lot of issues of what this is in certain areas of code:


  • 对于非严格函数,窗口

  • 用于严格函数, 未定义

  • 用于构造函数, this 是对象文字中的构造对象

  • 是直接封闭对象

  • for nonstrict functions, this is window
  • for strict functions, this is undefined
  • for constructor functions, this is the constructed object
  • within an object literal, this is the immediate enclosing object

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

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

如果你将它们作为一个对象传递,那么你可以迭代对象及其键而不是原始变量名。然而,在这种情况下,这比治疗更具破坏性。

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.

这篇关于使用JavaScript获取变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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