Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

javascript - 通用评估JavaScript(Evaluation for all purposes JavaScript)

I want an eval() function which will calculate brackets as same as normal calculations but here is my code(我想要一个eval()函数,该函数将与普通计算一样计算方括号,但这是我的代码)

 var str = "2(3)+2(5)+7(2)+2" var w = 0; var output = str.split("").map(function(v, i) { var x = "" var m = v.indexOf("(") if (m == 0) { x += str[i - 1] * str[i + 1] } return x; }).join("") console.log(eval(output)) 

Which takes the string str as input but outputs 61014 and whenever I try evaluating the output string, it remains same.(它以字符串str作为输入但输出61014,并且每当我尝试评估输出字符串时,它都保持不变。)

  ask by CoderBittu translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Obligatory " eval() is evil"(强制性的“ eval()是邪恶的”)

In this case, you can probably parse the input.(在这种情况下,您可能可以解析输入。)

Something like...(就像是...)

 var str = "2(3)+2(5)+7(2)+2"; var out = str.replace(/(\d+)\((\d+)\)/g,(_,a,b)=>+a*b); console.log(out); while( out.indexOf("+") > -1) { out = out.replace(/(\d+)\+(\d+)/g,(_,a,b)=>+a+(+b)); } console.log(out); 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...