Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
112
rated 0 times [  116] [ 4]  / answers: 1 / hits: 19183  / 10 Years ago, fri, march 21, 2014, 12:00:00

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

More From » arrays

 Answers
57

If you are doing this in the browser, one possible solution would be to do:



function setArray(a, b, c){
window['Array' + a][b] = c;
}

setArray('Top', 5, 100);


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:



var arrays = {
ArrayTop: [],
ArrayNorth: []
};

function setArray(a, b, c){
arrays['Array' + a][b] = c;
}

setArray('Top', 5, 100);


I would not recommend using eval. Eval is not meant for this kind of dynamic evaluation and it is a huge performance hit.


[#71861] Thursday, March 20, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kamronr

Total Points: 749
Total Questions: 110
Total Answers: 122

Location: Dominica
Member since Sat, Nov 5, 2022
2 Years ago
;