如何将variables名称转换为JavaScript中的string?

有没有办法将variables名称转换为JavaScript中的string? 更具体地说:

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

现在,在我经历数组时,我需要将variables名(而不是它们的值)作为string – 这将是“a”或“b”或“c”。 我真的需要它是一个string,所以它是可写的。 我怎样才能做到这一点?

使用Javascript对象文字:

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

你可以像这样遍历它:

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

并访问像这样的对象的属性:

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

你可以做的是这样的:

 var hash = {}; hash.a = 1; hash.b = 2; hash.c = 'hello'; for(key in hash) { // key would be 'a' and hash[key] would be 1, and so on. } 

Goptyclosures三联的东西(哪个谢谢)…

 (function(){ (createSingleton = function(name){ // global this[name] = (function(params){ for(var i in params){ this[i] = params[i]; console.log('params[i]: ' + i + ' = ' + params[i]); } return this; })({key: 'val', name: 'param'}); })('singleton'); console.log(singleton.key); })(); 

只是认为这是一个很好的小自主模式…希望它有帮助! 谢谢三联!