js函数实现简单计算器
实现基础四则运算
创建一个函数,接收两个数字和一个运算符(+、-、*、/),返回计算结果。使用switch结构处理不同运算符:
function basicCalculator(num1, operator, num2) {
switch (operator) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num2 !== 0 ? num1 / num2 : 'Error: Division by zero';
default:
return 'Error: Invalid operator';
}
}
处理连续运算
通过数组存储输入序列,使用reduce方法实现连续运算。假设输入格式为[5, '+', 3, '*', 2]:

function chainedCalculator(operations) {
return operations.reduce((acc, curr, index, arr) => {
if (typeof curr === 'string') {
const nextNum = arr[index + 1];
return basicCalculator(acc, curr, nextNum);
}
return acc;
}, operations[0]);
}
支持优先级运算
引入括号和运算符优先级处理。使用两个栈(数字栈和运算符栈)实现:
function advancedCalculator(expression) {
const tokens = expression.match(/(\d+|\+|-|\*|\/|\(|\))/g);
const values = [];
const ops = [];
const precedence = { '+': 1, '-': 1, '*': 2, '/': 2 };
tokens.forEach(token => {
if (!isNaN(token)) {
values.push(parseFloat(token));
} else if (token === '(') {
ops.push(token);
} else if (token === ')') {
while (ops[ops.length - 1] !== '(') {
applyOp(values, ops);
}
ops.pop();
} else {
while (ops.length && precedence[ops[ops.length - 1]] >= precedence[token]) {
applyOp(values, ops);
}
ops.push(token);
}
});
while (ops.length) {
applyOp(values, ops);
}
return values.pop();
}
function applyOp(values, ops) {
const b = values.pop();
const a = values.pop();
const op = ops.pop();
values.push(basicCalculator(a, op, b));
}
添加事件监听示例
HTML中绑定按钮点击事件,使用eval快速实现(注意安全风险):

<input type="text" id="display" readonly>
<button onclick="appendToDisplay('1')">1</button>
<!-- 其他数字/运算符按钮 -->
<script>
let currentInput = '';
function appendToDisplay(value) {
currentInput += value;
document.getElementById('display').value = currentInput;
}
function calculate() {
try {
const result = eval(currentInput);
document.getElementById('display').value = result;
currentInput = String(result);
} catch {
document.getElementById('display').value = 'Error';
currentInput = '';
}
}
</script>
安全增强方案
替代eval的方案,使用Function构造函数限制作用域:
function safeEval(expr) {
try {
return new Function('return ' + expr)();
} catch {
return NaN;
}
}
支持科学计算功能
扩展运算符处理,添加^幂运算和Math函数支持:
function scientificCalculator(expr) {
const processed = expr
.replace(/\^/g, '')
.replace(/sqrt\(/g, 'Math.sqrt(')
.replace(/sin\(/g, 'Math.sin(');
return safeEval(processed);
}






