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

HTML/JS如何实现字符串数学表达式求值并修复计算器undefined报错

问题原因

  • 输入框type属性设置错误:将input的type设为了number,该类型仅支持输入数字、小数点、科学计数法相关字符,无法输入+、-、*、/等运算符,输入运算符时会被直接拦截,导致拿到的表达式内容不符合预期。
  • new Function用法错误:当前写法生成的函数没有返回值,执行后自然返回undefined,需要在表达式前拼接return 语句,让函数把计算结果返回。

修复方案

  1. 把input标签的type="number"改为type="text"
  2. 修改new Function的调用逻辑,拼接return前缀
  3. 补充异常捕获逻辑,避免输入非法表达式时页面报错

修复后完整代码

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="utf-8">
        <title>Calculator: General (Under maintenance)</title>
        <style>
            h1{
                font-size: 100px;
                margin: auto;

            }
            div {
                font-size: 100px;
                position: absolute;
                top: 150px;
            }

        </style>
    </head>
    <button><a href="index.html">Go to home</a></button>
    <body>
     <h1>Calculator: General</h1>
     <input oninput="varChange()" id="equation" type="text">
     <div id="answer"></div>
     <script>
       function varChange(){
        var equation = document.getElementById("equation").value;
        var answer = document.getElementById("answer");
        try {
          answer.innerHTML = new Function('return ' + equation)()
        } catch (e) {
          answer.innerHTML = ''
        }
       }
     </script>
    </body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 02:51:04