0

I have a number of arrays in a javascript file The array that I want to use in my calculations is:

 var planets_num = []

If I want to use a certain array, I simply use:

  arraytouse = planets_num

What I want to do is use an input:

 <input type="text" id="mynewtext" value="Enter array name to use">

and then a function to get the value of "mynewtext":

 function getnewform1 () {
 newtext=document.getElementById('mynewtext').value
 . . .
 }

let's say that the var newtext = "abc" I then want:

 abc = planets_num

i.e. the values from the array abc to be placed in the planets_num array

Hope this makes sense

TIA

4
  • it's a good idea to use camelCase for naming Commented Oct 29, 2013 at 22:37
  • Have you tried using an eval. Commented Oct 29, 2013 at 22:38
  • 1
    Use some object to store the custom values, say scope, so you can write scope[name] = planets_num Commented Oct 29, 2013 at 22:39
  • @btoueg Yes, eval works -> array_name=eval(newtext) along with planets_num=array_name Commented Oct 29, 2013 at 22:51

3 Answers 3

2

If planets_num is in global scope, you can also refer to it like this:

arraytouse = window['planets_num'];

Variables on objects are also indexable values on that object by the same name. For global scope variables, they're on the window object.

So you could do something like this:

arraytouse = window[document.getElementById('mynewtext').value];

If the arrays aren't in global scope then you can organize them as properties on some object and reference that object in the same way:

arraytouse = objectOfArrays[document.getElementById('mynewtext').value];
Sign up to request clarification or add additional context in comments.

1 Comment

Yes arraytouse = window[document.getElementById('mynewtext').value] along with planets_num=arraytouse also works
0

@David answer is cleaner is more efficient, but here is an alternative with an eval:

var my_array = [];

$("button")[0].onclick = function()
{
    var input_text = $("input")[0].value;
    var array_input = eval(input_text);
}

The fiddle is here:

http://jsfiddle.net/W3NW9/3/

1 Comment

That is a very ugly alternative.
0

Rather than creating global variables, you should consider using an object and properties:

var data = {
  planets_num: [],
  another_arr:[]
}

Now you can do:

var arraytouse = data[document.getElementById('mynewtext').value];

but of course you should be writing robust code like:

var input = document.getElementById('mynewtext');

// Make sure an element was found before trying to access its value
var arraytouse = input && data[input.value];

// Make sure the value resolved to something truthy before
// trying to use it
if (arraytouse) {
  ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.