You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将变量作为运算符,编写实现两数运算的JavaScript函数?

实现你的JavaScript运算函数

嘿,这事儿不难!我给你两种常见的实现方式,你可以根据需求选:

方法1:使用Switch语句(直观易懂)

这种方式逻辑清晰,适合刚接触的开发者,能明确看到每个运算符对应的处理逻辑:

function result(firstnum, secnum, operator) {
  // 先简单校验参数类型(可选但推荐)
  if (typeof firstnum !== 'number' || typeof secnum !== 'number') {
    throw new Error('firstnum和secnum必须是数字类型');
  }

  switch(operator) {
    case '+':
      return firstnum + secnum;
    case '-':
      return firstnum - secnum;
    case '*':
      return firstnum * secnum;
    case '/':
      // 处理除数为0的情况
      if (secnum === 0) {
        throw new Error('除数不能为0');
      }
      return firstnum / secnum;
    case '%':
      return firstnum % secnum;
    default:
      throw new Error(`不支持的运算符:${operator}`);
  }
}

方法2:使用对象映射(简洁易扩展)

如果以后要加更多运算符,这种方式只需要在对象里新增键值对就行,代码更简洁:

function result(firstnum, secnum, operator) {
  // 参数校验
  if (typeof firstnum !== 'number' || typeof secnum !== 'number') {
    throw new Error('firstnum和secnum必须是数字类型');
  }

  const operations = {
    '+': (a, b) => a + b,
    '-': (a, b) => a - b,
    '*': (a, b) => a * b,
    '/': (a, b) => {
      if (b === 0) throw new Error('除数不能为0');
      return a / b;
    },
    '%': (a, b) => a % b
  };

  // 检查是否支持该运算符
  if (!operations.hasOwnProperty(operator)) {
    throw new Error(`不支持的运算符:${operator}`);
  }

  // 执行对应的运算
  return operations[operator](firstnum, secnum);
}

使用示例

不管哪种方法,调用方式都是一样的:

console.log(result(5, 3, '+')); // 输出8
console.log(result(10, 2, '/')); // 输出5

两种方法都加了参数校验和错误处理,避免程序因为非法输入崩溃,你可以根据自己的场景调整校验逻辑~

内容的提问来源于stack exchange,提问作者user9735220

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:33:13