简体   繁体   English

如何清理JS评估输入?

[英]How Do I Sanitize JS eval Input?

a="79 * 2245 + (79 * 2 - 7)";
b="";
c=["1","2","3","4","5","6","7","8","9","0","+","-","/","*"];
for (i=1;i<a.length;i++){
  for (ii=1;i<c.length;i++){
    b=(a.substring(0,i))+(c[ii])+(a.substring(i+1,a.length));
    alert(eval(b.replace(" ","")));
  }
}

I need to find out how to make it so that when I use eval, I know that the input will not stop the script, and if it would normally crash the script to just ignore it. 我需要弄清楚如何制作它,以便在使用eval时知道输入不会停止脚本,并且如果它通常会使脚本崩溃而忽略它。 I understand that eval is not a good function to use, but I want a quick and simple method by which I can solve this. 我知道eval并不是一个好函数,但是我想要一种快速简单的方法来解决此问题。 The above code tries to output all of the answers with all of the possible replacements for any digit, sign or space in the above. 上面的代码尝试输出所有答案,并对上面的任何数字,符号或空格进行所有可能的替换。 i represents the distance through which it has gone in the string and ii represents the symbol that it is currently checking. i代表它在字符串中经过的距离,ii代表它当前正在检查的符号。 a is the original problem and b is the modified problem. a是原始问题,b是修改后的问题。

Try catching the exception eval might throw, like this: 尝试捕获eval可能引发的异常,如下所示:

try{
  alert(eval(b.replace(" ","")));
} catch (e){
  //alert(e);
}

You can check for a few special cases and avoid some behaviors with regex or the like, but there is definitely no way to 'if it would normally crash just ignore it' 您可以检查一些特殊情况,并避免使用正则表达式等行为,但是绝对没有办法“如果通常会崩溃,那就忽略它”。

That is akin to the halting problem, as mellamokb refers to. 正如melamokb所指,这类似于停止问题。 And theres no way to know ipositively fa script runs to completion besides running it. 而且除了运行脚本外,没有办法确切地知道fa脚本是否已完成。

One should be very careful to vet any strings that go to eval , and keep user input out of them as much as possibl except for real simple and verifiable things like an integer value. 人们应该非常谨慎地审查所有传递给eval字符串,并让用户输入尽可能多的字符串,除了真正的简单且可验证的东西(例如整数值)。 If you can find a way around eval altogether than all the better. 如果您能找到一种完全绕过eval的方法,那就更好了。

For the calculation example you show its probably best to parse it properly into tokens and go from there rather than evaluate in string form. 对于计算示例,您可能会展示出将其正确解析为标记并从那里进行而不是以字符串形式求值的最佳方法。

PS - if you really want to check out these one-off's to the expression in a , it is a somewhat interesting use of eval eespite its faults. PS-如果您真的想检查a表达式中a这些一次性a ,那么eval espite尽管有其缺点,但却是一种有趣的用法。 cam you explain why you are trimming the whitespace imediately before evaluation? cam,您解释一下为什么在评估之前立即修剪空白吗? i dont believe i can think of a situation where it effects the results. 我不相信我能想到会影响结果的情况。 for (at least most) valid expressions it makes no difference, and while it might alter some of the invalid cases i cant think of a case where it does so meaningfully 对于(至少大多数)有效表达式,它没有任何区别,尽管它可能会改变一些无效情况,但我想不出有意义的情况

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM