简单 Calculator
你将构建什么
`calculate(, op, b)` 函数那个 supports +, -, *, / and 返回 numeric result, 使用 guard 针对 division 通过零.
学习目标
- 定义函数使用多个参数
- Use conditional or match 到选择操作
- 返回值 从函数
- Handle 边缘情况 (division 通过零)
前置要求
- 变量 and 数据类型 (数字)
- 如果/else or 切换/match 语句
- 函数定义概念
步骤
- 1
定义函数 signature
创建函数
calculate(, op, b)哪里 `andb是数字 andop` 是字符串如 "+", "-", "*", "/". signature tells caller 精确地什么到 provide.代码function calculate(a, op, b) { // body comes next }预期结果
函数 exists and 能是 called, 但返回无 yet.
- 2
选择操作
内部函数, 分支 on
opand 执行 matching arithmetic. Returning 内部每个分支 keeps logic flat and readable.代码if (op === "+") return a + b; if (op === "-") return a - b; if (op === "*") return a * b; if (op === "/") return a / b;预期结果
Calling calculate(4, "+", 5) 返回 9; calculate(10, "*", 3) 返回 30.
- 3
Guard division 通过零
之前划分, 检查 whether
b === 0and 返回 safe 值 or 消息. 这个 prevents 无穷大 or 运行时错误从 leaking 到 caller.代码if (op === "/") { if (b === 0) return "Cannot divide by zero"; return a / b; }预期结果
calculate(5, "/", 0) 返回错误消息相反的 无穷大.
提示
顺序 matters: 检查零 情况之前执行 division.
- 4
测试所有运算符
Call 函数一次 for 每个运算符 and print results. 测试每个分支是 如何你 确认函数是 完整.
代码console.log(calculate(4, "+", 5)); // 9 console.log(calculate(10, "-", 3)); // 7 console.log(calculate(6, "*", 7)); // 42 console.log(calculate(8, "/", 2)); // 4 console.log(calculate(5, "/", 0)); // Cannot divide by zero预期结果
Five 行的 输出: 9, 7, 42, 4, and division-通过-零消息.
- 5
添加输入验证
在主逻辑入口处添加输入验证:检查输入是否为有效数字、是否在允许范围内,对非法输入给出清晰提示而非崩溃。这是健壮程序的第一道防线。
代码function validateInput(value, min, max) { if (typeof value !== "number" || Number.isNaN(value)) { throw new Error(`Invalid input: ${value} is not a number`); } if (value < min || value > max) { throw new Error(`Input ${value} out of range [${min}, ${max}]`); } return value; } // Usage const input = validateInput(rawInput, 1, 100);预期结果
非法输入(非数字或超出范围)会抛出清晰的错误信息,合法输入正常通过。
提示
使用 try/catch 包裹调用处,向用户展示友好的错误提示。
自己动手试试
function calculate(a, op, b) {
// TODO: implement +, -, *, / with a zero-division guard
}
// Test calls
console.log(calculate(4, "+", 5));
console.log(calculate(8, "/", 0));function calculate(a, op, b) {
if (op === "+") return a + b;
if (op === "-") return a - b;
if (op === "*") return a * b;
if (op === "/") {
if (b === 0) return "Cannot divide by zero";
return a / b;
}
return "Unknown operator";
}
console.log(calculate(4, "+", 5)); // 9
console.log(calculate(10, "-", 3)); // 7
console.log(calculate(6, "*", 7)); // 42
console.log(calculate(8, "/", 2)); // 4
console.log(calculate(5, "/", 0)); // Cannot divide by zero你学到了什么
你构建函数那个接受参数, 分支 on 输入, 返回值, and handles 边缘情况 — four ingredients 的大多数真实函数.
相关资源
相关工具
- Math Evaluator
Compare 你的 calculator 使用完整表达式 evaluator.
相关速查表
- JavaScript Cheatsheet
函数语法 and arithmetic 运算符引用.
相关参考文档
- JavaScript Math
Arithmetic 操作 and 数字 handling 引用.
相关术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
相关错误
用大白话解释常见错误——什么意思、为什么发生、如何修复。