Is it possible to use a string as a nameholder for an array?
var myArray = ["a","b","c"];
var myPointer = "myArray";
console.log(myPointer[1]); //Should return "b"
Is it possible to use a string as a nameholder for an array?
var myArray = ["a","b","c"];
var myPointer = "myArray";
console.log(myPointer[1]); //Should return "b"
Yes, you can do this. I know of a few ways.
The first one would be to use eval()
, but I'm not going to discuss it since I think eval()
is evil.
One way to do it is to know which scope you are using. If you are using the window
scope, you can always do window[myPointer][1]
. If you are using a different scope, it's as easy as doing scope[myPointer][1]
.
If you don't have a scope or are unwilling to poison your window scope, you can always use something like this:
function blork (pointer) {
var arrays = {
number : [ 0, 1, 2, 3, 4, 5 ],
letters : [ 'a', 'b', 'c', 'd', 'e' ]
}
return arrays[pointer];
}
Edit: as noted in comments on other posts, this is not really a pointer. I assume you want to determine dynamically which array you want to use based on a string value.
I'm not sure why you would want to do that but you can use an object of arrays for this.
var myArray = ["a","b","c"];
var myObject = {"myArray": myArray};
var myPointer = "myArray";
console.log(myObject[myPointer][1]);
Primitive types, primarily strings/numbers/booleans are passed by value for efficiency purposes. Objects such as functions, objects, arrays and the like are passed by reference.
So you can make it an object and then use references to it.
See this question.
Hope that helps :)
I'm not sure why in your example it would return "b"... But i think a better approach to your question would be using a dictionary, actually it's pretty common data structure in JS.
so that in your case:
var myPoint = {
'a': 'm',
'b': 'y',
'c': 'p',
}
and so on..