如何在JavaScript中将变量名转换为字符串? [英] How to convert variable name to string in JavaScript?

查看:1695
本文介绍了如何在JavaScript中将变量名转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在javascript中将变量名转换为字符串?更具体地说:

Is there a way to convert variable names to strings in javascript? To be more specific:

var a = 1, b = 2, c = 'hello';
var array = [a, b, c];

现在,在我通过数组的某个时刻,我需要获取变量名称(而不是他们的名字)值)作为字符串 - 将是'a'或'b'或'c'。我真的需要它成为一个字符串,所以它是可写的。我该怎么做?

Now at some point as I go through the array, I need to get variable names (instead of their values) as strings - that would be 'a' or 'b' or 'c'. And I really need it to be a string so it is writeable. How can I do that?

推荐答案

使用Javascript对象文字:

Use a Javascript object literal:

var obj = {
    a: 1,
    b: 2,
    c: 'hello'
};

然后你可以这样遍历它:

You can then traverse it like this:

for (var key in obj){
    console.log(key, obj[key]);
}

并访问对象上的属性,如下所示:

And access properties on the object like this:

console.log(obj.a, obj.c);

这篇关于如何在JavaScript中将变量名转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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