Reputation: 97
the eval() does exactly what i want, but when i look at doc in MDN,it says
Do not ever use eval! eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, a third-party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.
eval() is also slower than the alternatives, since it has to invoke the JS interpreter, while many other constructs are optimized by modern JS engines.
Additionally, modern javascript interpreters convert javascript to machine code. This means that any concept of variable naming gets obliterated. Thus, any use of eval will force the browser to do long expensive variable name lookups to figure out where the variable exists in the machine code and set it's value. Additonally, new things can be introduced to that variable through eval() such as changing the type of that variable, forcing the browser to reevaluate all of the generated machine code to compensate. However, there (thankfully) exists a very good alternative to eval: simply using window.Function. As an example of how you convert code using evil eval() to using Function().
what is the better option for me. my code is like:
let aCount=0;
let bCount=0;
addCount=(option)=>{ //option either a or b
const choice=eval(option+"Count"); // then combine to aCount or bCount
choice++;
}
addCount(a);//aCount=1;
addCount(a);//aCount=2;
addCount(b);//bCount=1;
addCount(b);//bCount=2;
i try window[variable] before, but it doesn't return value i can't do thing like
const choice=window[option+"Count"]
it will return undefined. and i need to call choice many times so it's not gonna work for me to repeat window[variable].
Upvotes: 0
Views: 8323
Reputation: 2045
Besides "eval", there has some error in you example code, and I'm not going to explain for you.
And now we focus on "eval" in your example. If you do so, you'll find it won't work at all. You can only do this like eval(option + "Count++")
, rather than assign the value of aCount/bCount to a (CONST!) variable, and then increase that variable. The following code has logical problem:
let c = aCount;
c++; // aCount not changed
In my opinion, you can use "eval" in some special situation, as long as the code passed into "eval" is ABSOLUTELY trusted. In your example code, it corresponds this rule. (However, besides security, "eval" also has performance issue.)
Of course, you have other better choices to avoid using "eval". For example, use if/else or switch/case:
addCount=(option)=>{
if (option === 'a') aCount++;
else if (option === 'b') bCount++;
}
Or, you can use an object to hold all variables:
let obj = {aCount: 0, bCount: 0};
addCount=(option)=>{
obj[option + "Count"]++;
}
Upvotes: 1