Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eval is evil issue

Using JSlint to validate my javascript.

I am getting an error saying eval is evil! Why is this and is there an alternative I can use?

Here is an example of where I am using eval and would like a workaround for it.

I have an array like this:

var Resources = {
message_1: 'Message 1',
message_2: 'Message 2',
message_3: 'Message 3',
message_4: 'Message 4'
};

I have a function (functionResult) that returns a number, either 1, 2, 3 or 4. So what I want to do in the following line of code is get the Resource in the array that there message ends in the result of my function.

$('#divPresenter').html(eval($.validator.format('Resources.message_{0}', functionResult)));

Any ideas how I could remove eval and replace with something else?

like image 390
amateur Avatar asked Nov 28 '22 10:11

amateur


1 Answers

Instead of:

eval($.validator.format('Resources.message_{0}', functionResult))

just use:

Resources["message_" + functionResult]

All objects in JavaScript are really associative arrays (aka hashes), and the dot syntax (a.b) is just syntactic sugar for looking something up in the hash (a['b']). So you don't need eval at all; just build the key as a string, and look up your value using that key.

like image 126
Joe White Avatar answered Dec 05 '22 14:12

Joe White