如何在JavaScript中使变量可按名称作为字符串寻址? [英] How to make a variable addressable by name as string in JavaScript?
本文介绍了如何在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屋!
查看全文