“eval” 函数为什么返回 “undefined”?

huangapple go评论75阅读模式
英文:

Why does the "eval" function return "undefined"?

问题

I can provide a translation of the text you provided. Here it is:

我是编程的初学者,仍在学习过程中,我在练习JavaScript时遇到了一个问题,无法解决一个简单的计算器应用的问题。
我遇到的问题是,当我在计算器屏幕上输入像3+3这样的提示时,然后按等号时,我会得到结果3+3undefined。

首先,我检查了是否正确选择了变量,然后是否正确分配了监听器,然后尝试使用数学表达式评估,但都没有成功。我尝试的每一种方法都要么引发错误,要么返回undefined。

(以下是JavaScript和HTML代码片段,我不会翻译它们,因为您要求不翻译代码部分。)

如果您有关于代码的具体问题或需要帮助,请随时提出。

英文:

I'm beginner in coding, still in learning process, and I stuck on some problem creating a simple Calculator app as part of my practice in JS.
I have problem that when I make some prompt in the calculator screen as 3+3, than when I press equal I get the result 3+3undefined.

First I checked if I selected the variables correctly, then if I assigned add Listener correctly, then I tried to use math expression evaluation, but all without success. Everything I've tried always either throws Error or undefined.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

(function() {
  let screen = document.querySelector(&#39;#display&#39;);
  let buttons = document.querySelectorAll(&#39;.btn&#39;);
  let clear = document.querySelector(&#39;#clear&#39;);
  let equal = document.querySelector(&#39;#equals&#39;);

  buttons.forEach(function(button) {
    button.addEventListener(&#39;click&#39;, function(e) {
      let value = e.target.dataset.num;
      screen.value += value;
    });
  });

  equal.addEventListener(&#39;click&#39;, function(e) {
    if (screen.value === &#39;&#39;) {
      screen.value = &quot;&quot;;
    } else {
      let answer = eval(screen.value); /* every check says that there is a code error in this line.*/
      screen.value = answer;
    }
  });

  clear.addEventListener(&#39;click&#39;, function(e) {
    screen.value = &quot;&quot;;
  });
})();

<!-- language: lang-html -->

&lt;div class=&quot;calculator&quot;&gt;
  &lt;form&gt;
    &lt;input type=&quot;text&quot; class=&quot;screen&quot; id=&quot;display&quot;&gt;
  &lt;/form&gt;

  &lt;div class=&quot;buttons&quot;&gt;
    &lt;button type=&quot;button&quot; class=&quot;btn btn-yellow&quot; id=&quot;multiply&quot; data-num=&quot;*&quot;&gt;*&lt;/button&gt;
    &lt;button type=&quot;button&quot; class=&quot;btn btn-yellow&quot; id=&quot;divide&quot; data-num=&quot;/&quot;&gt;/&lt;/button&gt;
    &lt;button type=&quot;button&quot; class=&quot;btn btn-yellow&quot; id=&quot;subtract&quot; data-num=&quot;-&quot;&gt;-&lt;/button&gt;
    &lt;button type=&quot;button&quot; class=&quot;btn btn-yellow&quot; id=&quot;add&quot; data-num=&quot;+&quot;&gt;+&lt;/button&gt;
    &lt;button type=&quot;button&quot; class=&quot;btn&quot; id=&quot;nine&quot; data-num=&quot;9&quot;&gt;9&lt;/button&gt;
    &lt;button type=&quot;button&quot; class=&quot;btn&quot; id=&quot;eight&quot; data-num=&quot;8&quot;&gt;8&lt;/button&gt;
    &lt;button type=&quot;button&quot; class=&quot;btn&quot; id=&quot;seven&quot; data-num=&quot;7&quot;&gt;7&lt;/button&gt;
    &lt;button type=&quot;button&quot; class=&quot;btn&quot; id=&quot;decimal&quot; data-num=&quot;.&quot;&gt;.&lt;/button&gt;
    &lt;button type=&quot;button&quot; class=&quot;btn&quot; id=&quot;six&quot; data-num=&quot;6&quot;&gt;6&lt;/button&gt;
    &lt;button type=&quot;button&quot; class=&quot;btn&quot; id=&quot;five&quot; data-num=&quot;5&quot;&gt;5&lt;/button&gt;
    &lt;button type=&quot;button&quot; class=&quot;btn&quot; id=&quot;four&quot; data-num=&quot;4&quot;&gt;4&lt;/button&gt;
    &lt;button type=&quot;button&quot; class=&quot;btn btn-red&quot; id=&quot;clear&quot;&gt;C&lt;/button&gt;
    &lt;button type=&quot;button&quot; class=&quot;btn&quot; id=&quot;three&quot; data-num=&quot;3&quot;&gt;3&lt;/button&gt;
    &lt;button type=&quot;button&quot; class=&quot;btn&quot; id=&quot;two&quot; data-num=&quot;2&quot;&gt;2&lt;/button&gt;
    &lt;button type=&quot;button&quot; class=&quot;btn&quot; id=&quot;one&quot; data-num=&quot;1&quot;&gt;1&lt;/button&gt;
    &lt;button type=&quot;button&quot; class=&quot;btn btn-green&quot; id=&quot;equals&quot;&gt;=&lt;/button&gt;
    &lt;button type=&quot;button&quot; class=&quot;btn&quot; id=&quot;zero&quot; data-num=&quot;0&quot;&gt;0&lt;/button&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;script src=&quot;./script.js&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

答案1

得分: 2

你需要测试从按钮的数据属性中获取到实际值。如果使用委托会更容易,你可以直接使用按钮的textContent。我已经完全移除了数据属性。添加了一个清理器。

(function() {
  // 去除除了数字、()、-+/* 和 . 之外的所有字符
  const sanitizer = str => str.replace(/[^-()\d/*+.]/g, '');
  const screen = document.getElementById("display");
  document.querySelector(".buttons").addEventListener('click', function(e) {
    const tgt = e.target; // 点击的元素
    if (tgt.matches("#equals")) {
      if (screen.value !== "") { // 更简单的测试条件
        try { 
          let answer = eval(sanitizer(screen.value)); 
        }
        catch (e) {
          console.log(e.message);
          return;
        }
        screen.value = answer;
      }
    } else if (tgt.matches("#clear")) {
      screen.value = "";
    } else { 
      let value = tgt.textContent;
      if (value) screen.value += value;
    }
  });
})();
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" />
<div class="calculator">
  <form>
    <input type="text" class="screen" id="display">
  </form>

  <div class="buttons">
    <button type="button" class="btn btn-yellow" id="multiply">*</button>
    <button type="button" class="btn btn-yellow" id="divide">/</button>
    <button type="button" class="btn btn-yellow" id="subtract">-</button>
    <button type="button" class="btn btn-yellow" id="add">+</button><br/>
    <button type="button" class="btn">9</button>
    <button type="button" class="btn">8</button>
    <button type="button" class="btn">7</button>
    <button type="button" class="btn">.</button><br/>
    <button type="button" class="btn">6</button>
    <button type="button" class="btn">5</button>
    <button type="button" class="btn">4</button>
    <button type="button" class="btn btn-red" id="clear">C</button><br/>
    <button type="button" class="btn">3</button>
    <button type="button" class="btn">2</button>
    <button type="button" class="btn">1</button>
    <button type="button" class="btn btn-green" id="equals">=</button><br/>
    <button type="button" class="btn">0</button>
  </div>
</div>

<script src="./script.js"></script>
英文:

You need to test you get an actual value from the button's data attribute.

It makes it easier if you delegate and you can simply use the textContent of the buttons. I have removed the data attributes completely

Added a sanitiser

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

(function() {
// strip anything other than digits, (), -+/* and .
const sanitizer = str =&gt; str.replace(/[^-()\d/*+.]/g, &#39;&#39;);
const screen = document.getElementById(&quot;display&quot;);
document.querySelector(&quot;.buttons&quot;).addEventListener(&#39;click&#39;, function(e) {
const tgt = e.target; // what was clicked
if (tgt.matches(&quot;#equals&quot;)) {
if (screen.value !== &quot;&quot;) { // simpler test too
try { 
let answer = eval(sanitizer(screen.value)); 
}
catch (e) {
console.log(e.message);
return;
}
screen.value = answer;
}
} else if (tgt.matches(&quot;#clear&quot;)) {
screen.value = &quot;&quot;;
} else { 
let value = tgt.textContent;
if (value) screen.value += value;
}
});
})();

<!-- language: lang-html -->

&lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css&quot; /&gt;
&lt;div class=&quot;calculator&quot;&gt;
&lt;form&gt;
&lt;input type=&quot;text&quot; class=&quot;screen&quot; id=&quot;display&quot;&gt;
&lt;/form&gt;
&lt;div class=&quot;buttons&quot;&gt;
&lt;button type=&quot;button&quot; class=&quot;btn btn-yellow&quot; id=&quot;multiply&quot;&gt;*&lt;/button&gt;
&lt;button type=&quot;button&quot; class=&quot;btn btn-yellow&quot; id=&quot;divide&quot;&gt;/&lt;/button&gt;
&lt;button type=&quot;button&quot; class=&quot;btn btn-yellow&quot; id=&quot;subtract&quot;&gt;-&lt;/button&gt;
&lt;button type=&quot;button&quot; class=&quot;btn btn-yellow&quot; id=&quot;add&quot;&gt;+&lt;/button&gt;&lt;br/&gt;
&lt;button type=&quot;button&quot; class=&quot;btn&quot;&gt;9&lt;/button&gt;
&lt;button type=&quot;button&quot; class=&quot;btn&quot;&gt;8&lt;/button&gt;
&lt;button type=&quot;button&quot; class=&quot;btn&quot;&gt;7&lt;/button&gt;
&lt;button type=&quot;button&quot; class=&quot;btn&quot;&gt;.&lt;/button&gt;&lt;br/&gt;
&lt;button type=&quot;button&quot; class=&quot;btn&quot;&gt;6&lt;/button&gt;
&lt;button type=&quot;button&quot; class=&quot;btn&quot;&gt;5&lt;/button&gt;
&lt;button type=&quot;button&quot; class=&quot;btn&quot;&gt;4&lt;/button&gt;
&lt;button type=&quot;button&quot; class=&quot;btn btn-red&quot; id=&quot;clear&quot;&gt;C&lt;/button&gt;&lt;br/&gt;
&lt;button type=&quot;button&quot; class=&quot;btn&quot;&gt;3&lt;/button&gt;
&lt;button type=&quot;button&quot; class=&quot;btn&quot;&gt;2&lt;/button&gt;
&lt;button type=&quot;button&quot; class=&quot;btn&quot;&gt;1&lt;/button&gt;
&lt;button type=&quot;button&quot; class=&quot;btn btn-green&quot; id=&quot;equals&quot;&gt;=&lt;/button&gt;&lt;br/&gt;
&lt;button type=&quot;button&quot; class=&quot;btn&quot;&gt;0&lt;/button&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;./script.js&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

答案2

得分: 2

你的等号按钮触发了两个事件。一个是button.addEventListener,另一个是equal.addEventListener。当点击等号按钮时,它不应该运行按钮代码,因为data-num不存在。这就是为什么在你的eval中会出现undefined的原因。

一个更清晰的解决方案是检查数据属性data-num是否存在,而不是将data-num添加到等号按钮上。这样可以避免添加不必要的HTML。

buttons.forEach(function(button) {
  button.addEventListener('click', function(e) {
    if (e.target.dataset.hasOwnProperty('num')) {
      let value = e.target.dataset.num;
      screen.value += value;
    }
  });
});
英文:

Your equal button is firing two events.

One for button.addEventListener and the other equal.addEventListener. When the equal button is clicked it shouldn't run the button code because data-num does not exist. This is why undefined is being raised in your eval.

A cleaner solution is to check if the data attribute data-num exists instead of adding data-num to the equal button. Helps avoid adding unnecessary HTML.

  buttons.forEach(function(button) {
    button.addEventListener(&#39;click&#39;, function(e) {
      if (e.target.dataset.hasOwnProperty(&#39;num&#39;)) {
        let value = e.target.dataset.num;
        screen.value += value;
      }
    });
  });

答案3

得分: 0

这段代码修复了您的问题。

"equals button dose not have data-num property trigger undefine" 翻译为 "等于按钮没有data-num属性触发未定义"。

英文:

this code fix your problem

equals button dose not have data-num property trigger undefine

buttons.forEach(function(button) {
button.addEventListener(&#39;click&#39;, function(e) {
if(e.target.id !=&quot;equals&quot;){
let value = e.target.dataset.num;
screen.value += value;
} 
});
});

答案4

得分: 0

在您的HTML中的这行代码中:

   &amp;lt;button type=&quot;button&quot; class=&quot;btn btn-green&quot; id=&quot;equals&quot;&amp;gt;=&amp;lt;/button&amp;gt;

请添加 data-num=""

   &amp;lt;button type=&quot;button&quot; class=&quot;btn btn-green&quot; data-num=&quot;&quot; id=&quot;equals&quot;&amp;gt;=&amp;lt;/button&amp;gt;

说明: 您在JS中始终将 data-num 值添加到输入字段中,如果未定义,您将获得诸如 "9+9undefined" 的值,这不能由eval处理。如果添加一个空字符串,相同的值将是 "9+9"。

编辑(问题解决后)

正如您所说,您仍在学习,我认为您的实现和逻辑 看起来都很好

因此,这只是一个侧面说明: 如果您愿意,您可以让JS更多地完成“绘制”计算器的工作,并以稍微不同的方式监听事件,通过监听body上的点击事件,然后过滤出是否有任何点击实际命中某个按钮(这称为“委托事件处理”)。在JS中解决像简单计算器这样的问题有许多不同的方法,这就是编程变得有趣的地方。如果我赶时间,这是我会做的方式:)

另外: 确保 0.1 + 0.2 返回 0.3,这可能需要一些工作。请参阅:https://stackoverflow.com/questions/588004/is-floating-point-math-broken

<!-- 开始代码片段:js 隐藏:false 控制台:true Babel:false -->

<!-- 语言:lang-js -->
document.body.innerHTML = `
    &lt;div class=&quot;calculator&quot;&gt;
      &lt;input type=&quot;text&quot; placeholder=&quot;0&quot; readonly&gt;`
  + '&#39;789/456*123-C0.+()^=&#39;'.split('&#39;&#39;)
    .map(x => `&lt;div class=&quot;btn `
      + `${isNaN(x) && x !== &#39;.&#39; ? &#39;ctrl&#39; : &#39;&#39;}&quot;&gt;`
      + `${x}&lt;/div&gt;`).join('&#39;&#39;) + '&#39;&lt;/div&gt;&#39;;

document.body.addEventListener('click', e => {
  let btn = e.target.closest('.btn');
  if (!btn) { return; }
  let input = document.querySelector('input');
  let val = btn.innerText;
  val === 'C' && (input.value = '');
  val === '=' && (() => {
    try {
      input.value = eval(input.value.replaceAll('^', '**'))
        .toFixed(10).replace(/(\.[1-9]*)0{1,}$/g, '$1')
        .replace(/\.$/g, '');
    }
    catch (e) { input.value = ''; }
  })();
  !'C='.includes(val) && (input.value += val);
});

<!-- 语言:lang-css -->
.calculator {
  border-radius: 0.5vw;
  background-color: rgb(41, 111, 164);
  padding: 10px;
  display: inline-block;
}

.calculator::after {
  content: "";
  display: table;
  clear: both;
}

.btn {
  width: 3vw;
  height: 3vw;
  background-color: black;
  margin: 1px;
  color: white;
  float: left;
  font-size: 2vw;
  font-family: Verdana;
  padding: 0.8vw 0.5vw 0.2vw;
  text-align: center;
  cursor: pointer;
}

.btn:nth-child(4n+2) {
  clear: both;
}

.btn.ctrl {
  background-color: #333;
}

input {
  font-family: Verdana;
  font-size: 2vw;
  width: 16vw;
  height: 3vw;
  margin-bottom: 1vw;
  display: block;
  text-align: right;
}

<!-- 语言:lang-html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Calculator</title>
</head>
<body>
</body>
</html>

<!-- 结束代码片段 -->
英文:

On this line in your HTML:

&lt;button type="button" class="btn btn-green" id="equals"&gt;=&lt;/button&gt;

Add data-num=""

&lt;button type="button" class="btn btn-green" data-num="" id="equals"&gt;=&lt;/button&gt;

Explanation: You always add the data-num value to the input field in your JS, if it is undefined you will get a value such as "9+9undefined", and that can't be handled by eval. If you add an emptry string the same value will be "9+9".

Edit (after problem solved)

As you said, you are still learning, and I think your implementation and your logic looks just fine.

So this is only a sidenote: If you want to you can let JS do more of the work of 'drawing' the calculator and also listen to events a little bit differently, by listening to clicks on the body and then filter out if any of the clicks actually hit a certain button (this is called delegated event handling). There are so many flavors of how you solve something like a simple calculator in JS and that's what's makes programming fun. Here's how I would have done it, if in a hurry “eval” 函数为什么返回 “undefined”?

Also: Make sure that 0.1 + 0.2 returns 0.3, this may take some work. See: https://stackoverflow.com/questions/588004/is-floating-point-math-broken

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

document.body.innerHTML = `
&lt;div class=&quot;calculator&quot;&gt;
&lt;input type=&quot;text&quot; placeholder=&quot;0&quot; readonly&gt;`
+ &#39;789/456*123-C0.+()^=&#39;.split(&#39;&#39;)
.map(x =&gt; `&lt;div class=&quot;btn `
+ `${isNaN(x) &amp;&amp; x !== &#39;.&#39; ? &#39;ctrl&#39; : &#39;&#39;}&quot;&gt;`
+ `${x}&lt;/div&gt;`).join(&#39;&#39;) + &#39;&lt;/div&gt;&#39;;
document.body.addEventListener(&#39;click&#39;, e =&gt; {
let btn = e.target.closest(&#39;.btn&#39;);
if (!btn) { return; }
let input = document.querySelector(&#39;input&#39;);
let val = btn.innerText;
val === &#39;C&#39; &amp;&amp; (input.value = &#39;&#39;);
val === &#39;=&#39; &amp;&amp; (() =&gt; {
try {
input.value = eval(input.value.replaceAll(&#39;^&#39;, &#39;**&#39;))
.toFixed(10).replace(/(\.[1-9]*)0{1,}$/g, &#39;$1&#39;)
.replace(/\.$/g, &#39;&#39;);
}
catch (e) { input.value = &#39;&#39;; }
})();
!&#39;C=&#39;.includes(val) &amp;&amp; (input.value += val);
});

<!-- language: lang-css -->

.calculator {
border-radius: 0.5vw;
background-color: rgb(41, 111, 164);
padding: 10px;
display: inline-block;
}
.calculator::after {
content: &quot;&quot;;
display: table;
clear: both;
}
.btn {
width: 3vw;
height: 3vw;
background-color: black;
margin: 1px;
color: white;
float: left;
font-size: 2vw;
font-family: Verdana;
padding: 0.8vw 0.5vw 0.2vw;
text-align: center;
cursor: pointer;
}
.btn:nth-child(4n+2) {
clear: both;
}
.btn.ctrl {
background-color: #333;
}
input {
font-family: Verdana;
font-size: 2vw;
width: 16vw;
height: 3vw;
margin-bottom: 1vw;
display: block;
text-align: right;
}

<!-- language: lang-html -->

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot;&gt;
&lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;
&lt;title&gt;Calculator&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月7日 23:22:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76194774.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定