Tutorial :How do I remove eval() from the following code … - Javascript



Question:

I've been using eval in my code and I recently found out that there can be serious security issues If eval() is used inside Javascript. The most common scenario is where I'm using eval() to compose a variable name and then get the value of that variable like here;

var a = "2"        // could be any value    work(a);    function work(a)  {  var l1 = "something";  var l2 = "something else";  var l3 = "something different";    alert(eval("l"+a));  // alerts "something else"  };  

Are there any alternatives to eval() in a situation like this ??

I've tried using window["l"+a] but that will only work if the variables were global and also document.getElementById("l"+a) and that doesn't work either.

Any help greatly appreciated.

Thanks, Norman.


Solution:1

perhaps use an object or an array:

var obj = {      '1' : 'something',      '2' : 'something else',      'foo' : 'entirely different'  };  // access like this:  obj[1];            // "something"  obj['foo'];        // "entirely different"  var key = 'foo';  obj[key];          // "entirely different"  

or, as an array:

var arr = [      "something",      "something else",      "something different"  ];  arr[0] // something  arr[1] // something else  


Solution:2

use:

window["l"+a]  

e.g.

var a = "2"        // could be any value    work(a);    function work(a)  {  l1 = "something";  l2 = "something else";  l3 = "something different";    alert(window["l"+a]);  // alerts "something else"  };  

Alternatively, you could use an array or object notation (preferred as it doesn't pollute global)

var a = "2"        // could be any value    work(a);    function work(a)  {  var l = ["something", "something else", "something different" ];    alert(l[a]);  // alerts "something else"  };  


Solution:3

use a switch

function match(a)  {     switch(a)    {    case 1:     alert("something");    break;    case 2:     alert("something else");    break;    case 3:     alert("something different");    break;    default:     alert("No match!");    }    }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »