Evaluate string as a conditional statement

♀尐吖头ヾ 提交于 2019-12-25 08:57:24

问题


I am working on a c++ web-based IDE for beginners where one of it's core function is to let the user know the evaluation result (true or false) of the conditional statement they have on my contenteditable div.

Say i am already able to fetch the "fragment" (what i call it based on my architecture) that i wanted to evaluate and i already know the values of the variables...

Can you please suggest a way on how would i evaluate the text on the fragment as a conditional statement that will return either true or false...

Example

when var b = 5;

$('.frag').eq(1).text() //"if( (b>1) || (b==10) )"

after evaluation(what im asking for help) should return true

 $('.frag').eq(2).text() //"(b>1)" 

should return true

 **$('.frag').eq(3).text() //"(b==10)"

should return false

UPDATE

The problem i am seeing with eval is that if i have a var1 in the contenteditable div and i have a var1 in my code. I should put a header on the variables from the contenteditable then right? like sc_var1 to prevent messing up with var1 from my source code?


回答1:


You can use Eval like this:

var expression = $('.frag').eq(1).text();
var result = eval(expression);

However I generally do not recommend using eval because there is always a much better workaround.

if I get the bigger picture of your needs I would be able to provide a better solution.



来源:https://stackoverflow.com/questions/18842283/evaluate-string-as-a-conditional-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!