当前位置:首页 > JavaScript

js实现简单计算器

2026-03-01 07:25:12JavaScript

实现简单计算器的基本结构

使用HTML和JavaScript可以快速构建一个基础计算器。以下是一个实现方案,包含数字输入、加减乘除运算和结果显示功能。

<!DOCTYPE html>
<html>
<head>
    <title>简单计算器</title>
    <style>
        #calculator {
            width: 200px;
            margin: 50px auto;
            border: 1px solid #ccc;
            padding: 10px;
            text-align: center;
        }
        #display {
            width: 100%;
            height: 40px;
            margin-bottom: 10px;
            text-align: right;
        }
        button {
            width: 40px;
            height: 40px;
            margin: 5px;
        }
    </style>
</head>
<body>
    <div id="calculator">
        <input type="text" id="display" disabled>
        <div>
            <button onclick="appendToDisplay('7')">7</button>
            <button onclick="appendToDisplay('8')">8</button>
            <button onclick="appendToDisplay('9')">9</button>
            <button onclick="appendToDisplay('/')">/</button>
        </div>
        <div>
            <button onclick="appendToDisplay('4')">4</button>
            <button onclick="appendToDisplay('5')">5</button>
            <button onclick="appendToDisplay('6')">6</button>
            <button onclick="appendToDisplay('*')">*</button>
        </div>
        <div>
            <button onclick="appendToDisplay('1')">1</button>
            <button onclick="appendToDisplay('2')">2</button>
            <button onclick="appendToDisplay('3')">3</button>
            <button onclick="appendToDisplay('-')">-</button>
        </div>
        <div>
            <button onclick="appendToDisplay('0')">0</button>
            <button onclick="appendToDisplay('.')">.</button>
            <button onclick="calculate()">=</button>
            <button onclick="appendToDisplay('+')">+</button>
        </div>
        <div>
            <button onclick="clearDisplay()" style="width: 100px;">C</button>
        </div>
    </div>

    <script>
        function appendToDisplay(value) {
            document.getElementById('display').value += value;
        }

        function clearDisplay() {
            document.getElementById('display').value = '';
        }

        function calculate() {
            try {
                const result = eval(document.getElementById('display').value);
                document.getElementById('display').value = result;
            } catch (error) {
                document.getElementById('display').value = 'Error';
            }
        }
    </script>
</body>
</html>

功能扩展与改进

上述基础实现可以进一步优化和扩展:

// 改进计算函数,增加输入验证
function calculate() {
    const input = document.getElementById('display').value;
    if (!input) return;

    try {
        // 替换×为*,÷为/,兼容不同符号
        const expression = input.replace(/×/g, '*').replace(/÷/g, '/');
        // 使用Function构造器替代eval更安全
        const result = new Function('return ' + expression)();
        document.getElementById('display').value = result;
    } catch {
        document.getElementById('display').value = 'Error';
    }
}

// 添加键盘支持
document.addEventListener('keydown', function(event) {
    const key = event.key;
    if (/[0-9\.\+\-\*\/]/.test(key)) {
        appendToDisplay(key);
    } else if (key === 'Enter') {
        calculate();
    } else if (key === 'Escape') {
        clearDisplay();
    }
});

使用模块化设计

对于更复杂的计算器,可以采用面向对象的方式:

class Calculator {
    constructor() {
        this.currentInput = '';
        this.previousInput = '';
        this.operation = null;
    }

    appendNumber(number) {
        this.currentInput = this.currentInput.toString() + number.toString();
    }

    chooseOperation(op) {
        if (this.currentInput === '') return;
        if (this.previousInput !== '') {
            this.compute();
        }
        this.operation = op;
        this.previousInput = this.currentInput;
        this.currentInput = '';
    }

    compute() {
        let computation;
        const prev = parseFloat(this.previousInput);
        const current = parseFloat(this.currentInput);
        if (isNaN(prev) || isNaN(current)) return;

        switch (this.operation) {
            case '+':
                computation = prev + current;
                break;
            case '-':
                computation = prev - current;
                break;
            case '*':
                computation = prev * current;
                break;
            case '/':
                computation = prev / current;
                break;
            default:
                return;
        }
        this.currentInput = computation;
        this.operation = null;
        this.previousInput = '';
    }

    clear() {
        this.currentInput = '';
        this.previousInput = '';
        this.operation = null;
    }
}

注意事项

使用eval函数存在安全风险,在生产环境中应避免直接使用。可以考虑以下替代方案:

  • 使用数学表达式解析库(如math.js)
  • 手动解析表达式并计算
  • 使用Function构造器(比eval稍安全但仍需谨慎)

对于更复杂的科学计算器,需要实现:

  • 括号优先级处理
  • 三角函数等高级运算
  • 内存功能(M+、M-等)
  • 历史记录功能

js实现简单计算器

标签: 计算器简单
分享给朋友:

相关文章

实现简单vue

实现简单vue

实现一个简单的 Vue.js 框架 Vue.js 的核心功能包括数据绑定、响应式系统和虚拟 DOM。以下是一个简化版的 Vue 实现,涵盖基本功能。 数据响应式系统 使用 Object.define…

vue简单实现

vue简单实现

Vue 简单实现步骤 安装 Vue.js 最新版本: npm install vue@latest 创建 Vue 实例: import { createApp } from 'vue' co…

vue实现简单分页

vue实现简单分页

实现基础分页功能 在Vue中实现简单分页需要几个核心步骤:数据分片、页码计算、翻页逻辑。以下是一个基于Vue 3的示例实现方案: <template> <div>…

vue实现计算器

vue实现计算器

Vue 实现计算器的方法 使用 Vue 实现计算器可以充分利用其响应式数据和组件化特性。以下是一个简单的实现方案: 创建 Vue 项目 使用 Vue CLI 或 Vite 初始化项目: n…

vue实现简单登录验证

vue实现简单登录验证

实现登录表单基础结构 使用Vue的模板语法构建登录表单,包含用户名和密码输入框及提交按钮。表单需绑定v-model实现双向数据绑定,并监听submit事件。 <template> &…

vue怎么实现简单登录

vue怎么实现简单登录

Vue实现简单登录功能 使用Vue 2或Vue 3均可实现基础登录逻辑,以下是关键实现步骤: 创建登录表单组件 在Login.vue中设置用户名和密码输入框,绑定v-model数据: <te…