当前位置:首页 > JavaScript

js实现简单计算器

2026-01-30 16:21:45JavaScript

实现基础功能

创建一个HTML文件,包含数字按钮、运算符按钮和显示结果的输入框。基本结构如下:

<!DOCTYPE html>
<html>
<head>
    <title>简易计算器</title>
    <style>
        #calculator {
            width: 200px;
            margin: 0 auto;
            text-align: center;
        }
        button {
            width: 40px;
            height: 40px;
            margin: 5px;
        }
        #result {
            width: 180px;
            height: 40px;
            margin-bottom: 10px;
            text-align: right;
        }
    </style>
</head>
<body>
    <div id="calculator">
        <input type="text" id="result" readonly>
        <button onclick="appendToResult('7')">7</button>
        <button onclick="appendToResult('8')">8</button>
        <button onclick="appendToResult('9')">9</button>
        <button onclick="appendToResult('/')">/</button>
        <button onclick="appendToResult('4')">4</button>
        <button onclick="appendToResult('5')">5</button>
        <button onclick="appendToResult('6')">6</button>
        <button onclick="appendToResult('*')">*</button>
        <button onclick="appendToResult('1')">1</button>
        <button onclick="appendToResult('2')">2</button>
        <button onclick="appendToResult('3')">3</button>
        <button onclick="appendToResult('-')">-</button>
        <button onclick="appendToResult('0')">0</button>
        <button onclick="appendToResult('.')">.</button>
        <button onclick="calculate()">=</button>
        <button onclick="appendToResult('+')">+</button>
        <button onclick="clearResult()">C</button>
    </div>
    <script src="calculator.js"></script>
</body>
</html>

JavaScript逻辑实现

创建calculator.js文件,实现计算器核心功能:

js实现简单计算器

let currentInput = '';

function appendToResult(value) {
    currentInput += value;
    document.getElementById('result').value = currentInput;
}

function clearResult() {
    currentInput = '';
    document.getElementById('result').value = '';
}

function calculate() {
    try {
        const result = eval(currentInput);
        document.getElementById('result').value = result;
        currentInput = result.toString();
    } catch (error) {
        document.getElementById('result').value = 'Error';
        currentInput = '';
    }
}

增强功能实现

为计算器添加更多实用功能,如退格键和键盘支持:

js实现简单计算器

// 添加退格功能
function backspace() {
    currentInput = currentInput.slice(0, -1);
    document.getElementById('result').value = currentInput;
}

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

安全改进

使用更安全的计算方式替代eval:

function safeCalculate() {
    try {
        // 使用Function构造函数比eval更安全
        const result = new Function('return ' + currentInput)();
        if (isNaN(result) || !isFinite(result)) {
            throw new Error('Invalid calculation');
        }
        document.getElementById('result').value = result;
        currentInput = result.toString();
    } catch (error) {
        document.getElementById('result').value = 'Error';
        currentInput = '';
    }
}

完整代码整合

将上述改进整合到最终版本:

let currentInput = '';

function appendToResult(value) {
    currentInput += value;
    document.getElementById('result').value = currentInput;
}

function clearResult() {
    currentInput = '';
    document.getElementById('result').value = '';
}

function backspace() {
    currentInput = currentInput.slice(0, -1);
    document.getElementById('result').value = currentInput;
}

function calculate() {
    try {
        const result = new Function('return ' + currentInput)();
        if (isNaN(result) || !isFinite(result)) {
            throw new Error('Invalid calculation');
        }
        document.getElementById('result').value = result;
        currentInput = result.toString();
    } catch (error) {
        document.getElementById('result').value = 'Error';
        currentInput = '';
    }
}

document.addEventListener('keydown', function(event) {
    const key = event.key;
    if (/[0-9+\-*/.=]/.test(key)) {
        event.preventDefault();
        if (key === '=' || key === 'Enter') {
            calculate();
        } else {
            appendToResult(key);
        }
    } else if (key === 'Backspace') {
        event.preventDefault();
        backspace();
    } else if (key === 'Escape') {
        event.preventDefault();
        clearResult();
    }
});

这个实现包含了基础计算功能、键盘支持、错误处理和基本样式,可以根据需要进一步扩展功能或改进界面设计。

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

相关文章

vue 实现简单表格

vue 实现简单表格

以下是在 Vue 中实现简单表格的几种方法: 使用原生表格标签 通过 Vue 的数据绑定功能渲染表格数据: <template> <table> <the…

实现简单的vue

实现简单的vue

创建Vue项目 使用Vue CLI快速初始化项目,确保已安装Node.js和npm/yarn: npm install -g @vue/cli vue create my-vue-app cd my…

vue轮播图简单实现

vue轮播图简单实现

使用 Vue 实现轮播图 以下是一个基于 Vue 3 的简单轮播图实现方法,无需依赖第三方库。 基础结构 在 Vue 单文件组件中,通过 v-for 渲染图片列表,并用 CSS 控制切换效果。 &…

vue简单的列表实现

vue简单的列表实现

实现简单的 Vue 列表 在 Vue 中实现列表功能通常使用 v-for 指令。以下是一个基础的列表实现示例: <template> <div> <…

vue实现简单登录注册

vue实现简单登录注册

Vue 实现登录注册功能 项目初始化 使用 Vue CLI 创建项目 vue create auth-demo cd auth-demo 安装必要依赖 npm install axios vue-…

vue实现简单登录验证

vue实现简单登录验证

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