Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic array names javascript

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
like image 640
user1410288 Avatar asked Mar 21 '14 17:03

user1410288


3 Answers

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.

like image 78
tyronegcarter Avatar answered Sep 22 '22 00:09

tyronegcarter


Hash map will be a perfect tool:

var arrays = {
  top: [],
  left: [],
  right: [],
  bottom: []
};

function addToArray(name, index, value) {
  arrays[name][index] = value;
}

addToArray('top', 5, 100);

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).

like image 41
Feugy Avatar answered Sep 20 '22 00:09

Feugy


Why not indexing your array with an object?

var arrayNames=["top","left","right","bottom"]
var data=[1,2,3,4,5];
var arrays={};

arrayNames.forEach(function(x){
    arrays[x]=data;
});    

So you could get your Array via Name. If you randomize or autogenerate the names, no prob.

like image 36
Thomas Junk Avatar answered Sep 21 '22 00:09

Thomas Junk