js实现evaluation
JavaScript 实现表达式求值
在 JavaScript 中实现表达式求值可以通过多种方法完成,包括内置函数、手动解析和第三方库。以下是几种常见的方法:

使用 eval() 函数
eval() 是 JavaScript 内置函数,可以直接执行字符串形式的表达式。尽管简单,但存在安全风险,不建议用于用户输入的表达式。

const expression = "2 + 3 * 4";
const result = eval(expression);
console.log(result); // 输出 14
手动解析实现
手动解析表达式通常涉及将中缀表达式转换为后缀表达式(逆波兰表示法),再通过栈计算。以下是一个简化版的实现:
function evaluateExpression(expression) {
const tokens = expression.match(/\d+|\+|\-|\*|\/|\(|\)/g);
const output = [];
const operators = [];
const precedence = { '+': 1, '-': 1, '*': 2, '/': 2 };
tokens.forEach(token => {
if (!isNaN(token)) {
output.push(parseFloat(token));
} else if (token === '(') {
operators.push(token);
} else if (token === ')') {
while (operators.length && operators[operators.length - 1] !== '(') {
output.push(operators.pop());
}
operators.pop(); // 弹出 '('
} else {
while (operators.length && precedence[operators[operators.length - 1]] >= precedence[token]) {
output.push(operators.pop());
}
operators.push(token);
}
});
while (operators.length) {
output.push(operators.pop());
}
const stack = [];
output.forEach(token => {
if (typeof token === 'number') {
stack.push(token);
} else {
const b = stack.pop();
const a = stack.pop();
switch (token) {
case '+': stack.push(a + b); break;
case '-': stack.push(a - b); break;
case '*': stack.push(a * b); break;
case '/': stack.push(a / b); break;
}
}
});
return stack.pop();
}
console.log(evaluateExpression("2 + 3 * 4")); // 输出 14
使用第三方库
第三方库如 math.js 提供了更安全且功能丰富的表达式求值功能:
import { evaluate } from 'mathjs';
const result = evaluate("2 + 3 * 4");
console.log(result); // 输出 14
注意事项
- 安全性:避免直接使用
eval()处理用户输入,以防止代码注入攻击。 - 复杂性:手动解析适合学习,但实际项目中推荐使用库如
math.js或expr-eval。 - 扩展性:如果需要支持函数、变量等高级特性,手动解析会变得复杂,建议使用库。






