1. JavaScript eval() 函数:计算或执行参数。如果参数是表达式,则 eval() 计算表达式。如果参数是一个或多个 JavaScript 语句,则 eval() 执行这些语句。
var x = 10;
var y = 20;
var a = eval("x * ( y + x ) / ( x / 2 )");//60
var m='5 * 10';console.log(evea(m));//50
2. Java 实现
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class demo {
public static void test1() throws ScriptException {
String str = "(a >= 0 && a <= 5)";
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
engine.put("a", 4);
Object result = engine.eval(str);
System.out.println("结果类型:" + result.getClass().getName() + ",计算结果:" + result);
}
public static void test2() throws ScriptException {
String str = "43 * ( 2 + 1.4 ) + 2 * 32 / ( 3 - 2.1 )";
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval(str);
System.out.println("结果类型:" + result.getClass().getName() + ",计算结果:" + result);
}
public static void main(String[] args) throws ScriptException {
test1();
test2();
}
}