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

JavaScript eval函数无法执行两数运算,代码是否存在错误?

问题分析与修正

你的代码存在两处关键错误,导致无法完成运算:

  • 外层字符串使用了单引号',但模板字符串的变量插值${}只能在**反引号`**包裹的字符串中生效,单引号里的${eval(...)}会被直接当作普通文本输出,不会执行eval并插入结果。
  • 传给eval()的参数同样用单引号包裹,里面的${num1} ${operator} ${num2}不会被解析为实际的运算表达式,eval接收到的是未替换变量的字符串"${num1} ${operator} ${num2}",自然无法计算。

修正后的代码

方案1:使用模板字符串(推荐)

将外层和eval的参数都改用反引号包裹,让变量插值生效:

alert(`The result is ${eval(`${num1} ${operator} ${num2}`)}`);

方案2:字符串拼接

如果不习惯模板字符串,也可以用传统的字符串拼接方式:

alert('The result is ' + eval(num1 + ' ' + operator + ' ' + num2));

额外提醒:规避eval的安全风险

eval()会执行任意传入的代码,如果num1、num2或operator来自用户输入,可能存在代码注入风险。更安全的做法是用运算符映射对象替代eval:

const operators = {
  '+': (a, b) => a + b,
  '-': (a, b) => a - b,
  '*': (a, b) => a * b,
  '/': (a, b) => a / b
};
// 先验证运算符是否合法
if (operators[operator]) {
  alert(`The result is ${operators[operator](num1, num2)}`);
} else {
  alert('非法运算符');
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 08:45:54