Javascript dynamic array names

I have several arrays with similar names.

ArrayTop[]  
ArrayLeft[]   
ArrayRight[]  
ArrayWidth[]

I am trying to set a dynamic name in a function and then set the value.

I tried many ways to dynamically select the correct array, but did 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 install.

ArrayTop[5]=100
+4
source share
7 answers

If you do this in a browser, one of the possible solutions is:

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

setArray('Top', 5, 100);

I would recommend that your entire array be contained in some kind of object and not pollute the global namespace. So that 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 designed for such a dynamic assessment, and it is a huge success.

+3

:

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

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

addToArray('top', 5, 100);

.

:

  • eval. Eval .

  • . ( ).

+2

?

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

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

, . , .

+1

:

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

setarray('Top',5,100)

. 2D- - . , , , , .

0

:

var myArrays = { 
    top : arrayTop,
    left: arrayLeft,
    right: arrayRight,
    bottom: arrayBottom
}

, :

myArrays["top"][5] = 100;

- :

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

4 , :

myArrays["top"][0] = 100;

myArrays.top[0] = 100;

, top, left, right bottom ( ), :

function MyObj(top, left, right, bottom) {
   this.top = top;
   this.left = left;
   this.right = right;
   this.bottom = bottom;
}

var myArray = [];

myArray.push(new MyObj(1,2,3,4));
console.log(myArray[0]);

myArray[0].left = 7;
console.log(myArray[0]);

http://jsfiddle.net/UNuF8/

0

, Array String = > "Array".

var postfix = "Top"; 
var a = eval("new Array"+postfix);
a.push(100);
0

-

var someArr = {

};
someArr.ArrayTop = [];

function setarray(a, b, c) {

    var arrName = "Array" + a;
    someArr[arrName][b] = c;
}


setarray('Top', 5, 100)

alert(someArr.ArrayTop[5]);

, . fiddle

0

Source: https://habr.com/ru/post/1532883/


All Articles