0

Using jsbin.com tool to test Javascript code I used eval() function, but an warning from JSBin says "Eval is Evil". I did some searches about the use of eval() function and some sources says that is always possible avoid of use eval().

My code need access an array using parameters from other array. See this code:

var Collection = {
                  "cell"  : "value[3]", 
                  "lines" : "source[1..7]", 
                  "title" : "greeting"
                 };

var Data = {
            source : ["a", "b", "c"],

            value   : [
                       "done",
                       "easy", 
                       "f", 
                       "g", 
                       "h", 
                       "i", 
                       "j" 
                      ],

            greeting : "Hi!"         

       };

function Process()
 {
  var x = "cell";

  console.log("value[4] = " + Data.value[4]);
  console.log("C : " + Collection[x]);
  console.log("value['cell'] = " + eval("Data." + Collection[x]));
 }

The output is

value[4] = h
C : value[3]
value['cell'] = g

The recomendations says to access using dot notation, like I do in access to value[4], but the value to be accessed will go in a variable, like 'x', in this case with content "cell". This value is used to access Collection array, and select the value that will be used and Data array. I solve it using eval() function.

Are there a way to do this without eval() ??

  • See http://stackoverflow.com/a/14397052/1048572 – Bergi Feb 02 '13 at 16:14
  • How do your `cell` values look in general? – Bergi Feb 02 '13 at 16:16
  • Thanks @Bergi. I was thinking that always there are a way to avoid eval(). I don't know if I understand your question about 'cell', that is only a name that reference another variable name that I need to peek in another array. – Mauricio Lima Feb 05 '13 at 03:10
  • Yes, there is a way to avoid `eval` for this task and it should be used. I wanted to know how complex the format of those "variable names" can get - is it always just a property name plus an index number in square brackets? – Bergi Feb 05 '13 at 07:12

0 Answers0