// 这是一个简单的 JavaScript 计算器函数,可以执行基本的加、减、乘、除运算。
function calc(a, b, operator) {
// 检查操作数是否为数字
if (typeof a !== 'number' || typeof b !== 'number') {
return "Error: 参数必须是数字";
}
// 根据操作符执行相应的运算
switch (operator) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
// 检查除数是否为0
if (b === 0) {
return "Error: 除数不能为0";
}
return a / b;
default:
return "Error: 不支持的操作符";
}
}
// 示例调用
console.log(calc(10, 5, '+')); // 输出: 15
console.log(calc(10, 5, '-')); // 输出: 5
console.log(calc(10, 5, '*')); // 输出: 50
console.log(calc(10, 5, '/')); // 输出: 2
console.log(calc(10, 0, '/')); // 输出: Error: 除数不能为0
console.log(calc(10, 'a', '+')); // 输出: Error: 参数必须是数字
console.log(calc(10, 5, '%')); // 输出: Error: 不支持的操作符
这段代码实现了一个简单的计算器函数 calc,它接受两个数字参数和一个操作符(+, -, *, /),并返回相应的计算结果。此外,还包含了一些错误处理逻辑,确保输入有效。
上一篇:html/css/js 的关系
下一篇:js selection
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站