Question about eval () in javascript ... why is it evil and how can I accomplish the same thing without using it?

I have a script application that works correctly, but I have several eval () statements to make everything work. I really don’t understand why “eval is evil” as I keep reading, but what I really don’t understand is how to avoid using it when this is the only thing that does what I need for this.

In my script, I have a bunch of products. Each product has its own array of properties. There is also an array of all array names. When I run various functions, these arrays are used to create page content. The only method I found was to do this:

var schedule = {};  
$.each(productNameArray, function (i, name) {
    schedule = eval(name);
    // DO STUFF
});

Just using the name passes the string and does not read the actual array it refers to. Eval makes it work as an object.

So how to do this without using eval ()?

+3
source share
2 answers

What you do is parsing a JSON string (for example). This is one of the few cases when evalin fact it is not evil.

If you can trust the server 100%, from which the data comes to the client, this is not a real problem (we are talking about security problems with eval).

, eval(), global window object, cookies, DOM .. .

, eval - , - . eval() , ECMAscript. , , setTimeout

setTimeout("myfunction();", 2000); // don't do that

setTimeout(myfunction, 2000);

Javascript Javascript .

+1

Eval Evil.

Eval - , eval'd javascript- minifiers, - (, minifier - eval'd). , 99% eval'd , eval - , .

.

, , , , .

, . Eval .

, , obj[name]. ... .

+1

Source: https://habr.com/ru/post/1759119/


All Articles