I have a few arrays with like names.
ArrayTop[]
ArrayLeft[]
ArrayRight[]
ArrayWidth[]
I am trying to set the name dynamically in a function and then set value.
I have tried many ways of dynamically picking the right array but have not come up with a solution.
function setarray(a,b,c){
eval(Array+a+[b])=c
}
setarray('Top',5,100)
In this example i am trying to set.
ArrayTop[5]=100
You missed, that Array has to be a String => "Array". Then you can do
Why not indexing your array with an object?
So you could get your Array via Name. If you randomize or autogenerate the names, no prob.
try something like this
Hope this works. Here is the fiddle
Put all your arrays into an object:
And the to get an array you can just:
Or you can skip defining the arrays as global variables and just do something like:
Which initializes 4 empty arrays which you can populate:
or
However, if
top
,left
,right
andbottom
all are related (refering to the same object), it might make more sense to create an object with those properties and create a single array of those objects:http://jsfiddle.net/UNuF8/
Hash map will be a perfect tool:
I took the liberty to give more explicit names.
I suggest also two good practices:
do not use eval. Eval is not meant for this kind of dynamic evaluation. In your case, it's a performance killer
do not polute the global namespace. In browser environnement, avoid adding stuff to window (which is global).
If you are doing this in the browser, one possible solution would be to do:
I would recommend that all your array's be contained in some object and not pollute the global namespace. So it would be more like:
I would not recommend using eval. Eval is not meant for this kind of dynamic evaluation and it is a huge performance hit.