Skip to content Skip to sidebar Skip to footer

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 cu

Solution 1:

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 :-)

Solution 2:

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 ); //usepush; no need to specify an index
  }
}

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

Post a Comment for "Convert Variable Name To String In Javascript?"