在Javascript中将变量名转换为字符串?

时间:2011-11-02 16:33:26

标签: javascript arrays

我在Stack Overflow上看过其他一些关于此的帖子,但答案似乎总是创建一个具有键/值对的对象。在我目前的情况下,这似乎不是我需要的。我想做什么:我有不同的数组,可能包含用户名。我想检查每个数组,看看用户名是否作为值存在。如果是,我想要一个数组变量名称的字符串表示。例如:

var array = ['apple', 'orange', 'grape'];
var array2 = ['apple', 'pear', 'plumb']

member_arrays = new Array();
// I'd like this block to be dynamic in that i don't have to specify the array name 
// in the inArray or member_arrays[member_arrays.length+1] (just loop through my arrays
// and add a string representation of the array name to the member_arrays array)
if ($.inArray( 'apple', array ) != -1)
  member_arrays[member_arrays.length] = 'array';
if ($.inArray( 'apple', array2) != -1)
  member_arrays[member_arrays.length] = 'array2';
// etc...

2 个答案:

答案 0 :(得分:4)

你不能用JavaScript做到这一点。这就是为什么人们建议使用一个对象并将“变量”保留为对象中的属性。

顺便说一下,当你追加一个数组时,你只需要长度,而不是长度+ 1:

member_arrays[member_arrays.length] = 'array';

数组是从零开始的,因此“下一个”时隙始终是“长度”值。

编辑 - 好吧,有一种情况可以做到这一点:当你的变量是全局变量时。名为“x”的任何全局变量也可以称为“窗口”的属性(对于Web浏览器中的代码):

var x = 3;
alert(window['x']); // alerts "3"

为此,请避免使用全局变量: - )

答案 1 :(得分:1)

我不确定你为什么要这样做,但把它放在一边,这是一种接近你似乎正在寻找的方法。它确实使用了一个对象,正如其他人推荐的那样,但最终得到的“答案数组”包含通过测试的候选数组的名称。

你在样本中使用jQuery,所以我也这样做了。但您也可以使用纯JavaScript .indexOf()

var candidates = {
  'array' : ['apple', 'orange', 'grape'],
  'array2' : ['apple', 'pear', 'plumb']
};
var member_arrays = [];

for( var test in candidates ){
  if( $.inArray( 'apple', candidates[test] ) !== -1 ){ // could use .indexOf()
    member_arrays.push( test ); // use push; no need to specify an index
  }
}

console.log( member_arrays ); // -> ["array","array2"]
相关问题