tags:

views:

54

answers:

3

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.

+4  A: 

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"
};
Jonathan Fingland
+5  A: 

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
nickf
definately as the array. then the parameter is just an array index.
Eric Falsken
@Eric, yep I definitely agree that's the best option, though I wasn't sure whether the suffixed numbers were meaningful in the OP.
nickf
A: 

use a switch

function work(a) {

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

}

Bhanu