简体   繁体   中英

Convert variable name to string in Javascript?

I've seen a few other posts about this on Stack Overflow, but the answer always seems to be to create an object with key / value pairs. This doesn't seem to be what I need in my current situation. What I'm wanting to do: I have different arrays which could possibly contain a username. I want to check each array and see if the username is present as a value in them. If it is, I'd like a string representation of a name of the array variable. Example:

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...

You cannot do that in JavaScript. That's why people suggest using an object and keeping your "variables" as properties in the object.

By the way, when you're appending to an array, you want just the length, not length + 1:

member_arrays[member_arrays.length] = 'array';

Arrays are zero-based, so the "next" slot is always the "length" value.

edit — well, there is a case where you can do that: when your variables are global. Any global variable named "x" can also be referred to as a property of "window" (for code in a web browser):

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

Please avoid global variables for this purpose :-)

I'm not sure why you'd want to do things this way, but putting that aside, here's an approach that approximates what you seem to be looking for. It does use an object, as others have recommended, but you end up with the "answer array" containing the names of the candidate arrays passing the test.

You do use jQuery in your sample, so I've done so as well. But you can also use the plain JavaScript .indexOf() the same way.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM