EternalCuriosity
EternalCuriosity

Reputation: 79

Using eval Function To Access Arrays

I have successfully accessed different arrays and their elements using a for loop and the eval function as shown below:

var Array1 = [A,B,C,D];
var Array2 = [D,B,C,A];
var Array3 = [B,C,A,D];
var Array4 = [A,D,B,C];

for(var row = 1; row <=4; row++){
  for(var column = 0; column <=3; column++){
    if(row<4 && eval("Array" + row)[column] == eval("Array" + (row +1))[column]){
       console.log("Value of Array" + row + "column" + column + "is equal to" + "value of Array" + eval(row + 1) + "column" + column + "\n");
    }
  }
}

The question I have is, am I correctly using the eval function. If it is not the correct way to use the eval function how do I dynamically access different arrays in the for loop without using the eval function?

Upvotes: 0

Views: 584

Answers (2)

Blender
Blender

Reputation: 298176

I wouldn't say using eval like this is a good idea. eval is very rarely used because it's hard to debug and can be replaced with something easier to understand in most cases. It has valid use cases, but this isn't one of them.

Use an array of arrays instead:

var A = 2, B = 2, C = 3, D = 4;

var grid = [
    [A,B,C,D],
    [D,B,C,A],
    [B,C,A,D],
    [A,D,B,C]
]

for (var row = 0; row < grid.length; row++) {
    for (var column = 0; column < grid[0].length; column++) {
        if (row + 1 < grid.length && grid[row][column] === grid[row + 1][column]) {
            // they're equal
        }
    }
}

Upvotes: 1

Hydrothermal
Hydrothermal

Reputation: 5081

Use of eval like this, although it might work, is a bad idea and makes it very easy to write dangerous code. Since eval will execute its argument regardless of what is actually passed, bugs that result in passing the wrong argument can have much more serious consequences than they would if you weren't using eval. The answers to this SO question offer some more insight. Instead consider using an object of arrays:

var arrays = {
    Array1: [A,B,C,D],
    Array2: [D,B,C,A],
    Array3: [B,C,A,D],
    Array4: [A,D,B,C]
}

for(var row = 1; row <=4; row++){
  for(var column = 0; column <=3; column++){
    if(row<4 && arrays["Array" + row][column] == arrays["Array" + (row + 1)][column]){
       console.log("Value of Array" + row + "column" + column + "is equal to" + "value of Array" + (row + 1) + "column" + column + "\n");
    }
  }
}

Upvotes: 1

Related Questions