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

如何在JavaScript中检查变量是否为虚数?计算器替换NaN为错误提示

在JavaScript中处理计算器的复数运算错误提示

要避免计算器在复数运算时显示NaN,核心思路是提前预判非法运算场景或运算后校验结果,以下是具体实现方案:

一、运算前针对性检查(推荐)

这种方式能精准提示错误原因,用户体验更好。针对常见的会产生复数的运算场景,单独做输入校验:

1. 开平方运算

负数开平方会产生虚数,直接拦截并提示:

function sqrt(num) {
  if (typeof num !== 'number') return "错误:请输入有效数字";
  if (num < 0) {
    return "错误:负数无法进行实数开平方运算";
  }
  return Math.sqrt(num);
}

2. 对数运算

真数必须大于0,否则结果为复数:

function log(num, base = Math.E) {
  if (typeof num !== 'number' || typeof base !== 'number') return "错误:请输入有效数字";
  if (num <= 0) {
    return "错误:仅正数可进行对数运算";
  }
  if (base <= 0 || base === 1) {
    return "错误:对数底数必须大于0且不等于1";
  }
  return Math.log(num) / Math.log(base);
}

3. 反三角函数(反正弦/反余弦)

输入必须在[-1, 1]范围内,否则结果为复数:

function asin(num) {
  if (typeof num !== 'number') return "错误:请输入有效数字";
  if (num < -1 || num > 1) {
    return "错误:反正弦函数的输入范围必须在[-1, 1]之间";
  }
  return Math.asin(num);
}

function acos(num) {
  if (typeof num !== 'number') return "错误:请输入有效数字";
  if (num < -1 || num > 1) {
    return "错误:反余弦函数的输入范围必须在[-1, 1]之间";
  }
  return Math.acos(num);
}

4. 幂运算

负数的非整数次幂会产生复数,需校验:

function power(base, exponent) {
  if (typeof base !== 'number' || typeof exponent !== 'number') return "错误:请输入有效数字";
  if (base < 0 && !Number.isInteger(exponent)) {
    return "错误:负数仅能进行整数次幂运算";
  }
  return Math.pow(base, exponent);
}

二、运算后兜底检查

如果是处理用户输入的自由表达式(比如用eval解析),可以在运算后校验结果,覆盖所有未提前预判的场景:

function calculate(expression) {
  try {
    // 先过滤非法字符(可选,提升安全性)
    if (!/^[\d+\-*/^().\s]+$/.test(expression)) {
      return "错误:包含无效运算字符";
    }
    const result = eval(expression);
    // 检查是否为NaN(复数运算会返回NaN)
    if (Number.isNaN(result)) {
      return "错误:当前运算无法得到实数结果";
    }
    // 额外处理无穷大的情况(比如除以0)
    if (!isFinite(result)) {
      return "错误:运算结果超出实数范围";
    }
    return result;
  } catch (e) {
    return "错误:无效的运算表达式";
  }
}

注意事项

  • 优先使用运算前检查,能给用户更明确的错误指引;
  • 若使用eval处理表达式,务必做字符过滤,避免安全风险;
  • 所有函数都加入了基础的类型校验,防止非数字输入导致的异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 03:28:26