-1

I'm attempting to write a function to take a string as an input (some of the strings that come in will actually be the names of arrays), and will create an entry in an HTML menu with that string. The main trouble is that I have an array associated with each string, but the name of the array is the string + "txt". What I've done so far involves calling a first function, which takes arguments of the string, and the level into the array that it has read (since these are nested arrays), and the goal is to pass to another function, the string, and the string with the appended "txt", but I run into problems when I assign something a value of that "string + 'txt'" when the string is the name of an array because javascript will just add "txt" to the array as an element.

I've tried this:

function splitName(name, level) {
   var arg1 = name;
   var arg2 = name + "txt";
   generateMenu(name, arg1, arg2, level);
}

In short, I'm wondering if there is a way that I can pull out the name of the array as a string and manipulate that?

Please comment with any questions or if anything is unclear. I'm a little new to programming.

JoDraX
  • 109
  • 2
  • 1
    It's good habit to post some code as well, this way the community can see what you've accomplished and give a more accurate help! – G4bri3l Jun 26 '15 at 15:51
  • Thanks for the headsup! I added my attempts so far. – JoDraX Jun 26 '15 at 16:03
  • What do you mean when you say "(some of the strings that come in will actually be the names of arrays)", because from the behavior you explained you are passing an array to your function not a string. So the problem is not in this function but in the values you are passing to it. If you have var array_name = [....some data..] and then you pass array_name to your function then you passed an array not a string. Check this out http://stackoverflow.com/questions/4602141/variable-name-as-a-string-in-javascript – G4bri3l Jun 26 '15 at 16:15
  • I guess I didn't phrase my question appropriately then. But if I have passed an array to the function, is there any way to convert the name of that array into a string to by manipulated in the function? – JoDraX Jun 26 '15 at 16:19

1 Answers1

0

Here's what you can do:

If you can find a way to make the variable name a property value in an object like this,

var names = {
    blah1: 'name1',
    blah2: 'name2',
    blah3: 'name3'
};

you can access the values like this (which will be the array names):

for (var i in names){
    alert(i);
    alert(obj[i]);
}

I'll post again if I can find a way to do that.

For now,

Another post on this issue can be found here:

How to convert variable name to string in JavaScript?.

Community
  • 1
  • 1
Inaudible Jive
  • 139
  • 2
  • 8
  • From what it looks like, you need to define the arrays as properties in the object. Looks like you can't access the names otherwise. – Inaudible Jive Jun 26 '15 at 16:32