1

I would like to be able to reference an array by using a string, as such:

var arrayName = "people";

var people = [
    'image47.jpeg',
    'image48.jpeg',
    'image49.jpeg',
    'image50.jpeg',
    'image52.jpeg',
    'image53.jpeg',
    'image54.jpeg',
    'image55.jpeg',
]

function myFunc (arrayName)
{
    //arrayName is actually just a string that evaluates to "people", which then in turn would reference the var people, which is passed in.
}

Any thoughts on how to do this? Sorry if I'm missing something obvious.

2
  • var arrayName[] = people[]; and this needs to come after var people [ ]. Commented Mar 20, 2012 at 2:09
  • See this stackoverflow.com/questions/952457/… Commented Mar 20, 2012 at 2:13

3 Answers 3

2

You can simply create a global dictionary, like this:

var people = ['image47.jpeg', 'image48.jpeg'];
var cars = ['image3.png', 'image42.gif'];
var global_arrays = {
    people: people,
    cars: cars
};

function myFunc(arrayName) {
   var ar = global_arrays[arrayName];
   // Do something with ar
}

Note that the first line of myFunc makes it clear that this is just a complicated way of having myFunc accept the array itself in the first place. I strongly suggest that you do just that, like this:

function myFunc(ar) {
   // Do something with ar
}
myFunc(people);

This means that your code will be reusable by anyone else (say, a third-party plugin that wants to render giraffes) and not require any global variables.

Sign up to request clarification or add additional context in comments.

Comments

1

If your array is declared outside of a function, you can access it using the this keyword like so:

function myFunc(arrayname) {
    var itemzero = this[arrayname][0];
}

Comments

0
var arrayName = "people";

var people = [
    'image47.jpeg',
    'image48.jpeg',
    'image49.jpeg',
    'image50.jpeg',
    'image52.jpeg',
    'image53.jpeg',
    'image54.jpeg',
    'image55.jpeg',
]

function myFunc (arrayName)
{

 //Here you can use this or window obj To quote you array.
 //such as window[arrayName]

}

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.